本文在原文的基础上有所修改,原文请参考:
http://titanseason.iteye.com/blog/1471606 由于此blog不支持附件附件请到此处下载
http://my.oschina.net/bigyuan/blog/165464
1. 需要用的软件
OpenOffice 下载地址http://www.openoffice.org/
JodConverter 下载地址http://sourceforge.net/projects/jodconverter/files/JODConverter/,也可以直接从附件里面下载
2.启动OpenOffice的服务
安装完openoffice,安装服务
cd C:\Program Files (x86)\OpenOffice 4\program
执行
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
查看是否安装成功,查看端口对应的pid
netstat -ano|findstr "8100"
查看pid对应的服务程序名
tasklist|findstr "pid值"
3.将JodConverter相关的jar包添加到项目中
4. 下面是实现代码
附件里面有现成的可以用的项目示例,直接导入eclipse就可以运行
/** * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice下载地址为 * http://www.openoffice.org/ * * <pre> * 方法示例: * String sourcePath = "F:\\office\\source.doc"; * String destFile = "F:\\pdf\\dest.pdf"; * Converter.office2PDF(sourcePath, destFile); * </pre> * * @param sourceFile * 源文件, 绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, * .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc * @param destFile * 目标文件. 绝对路径. 示例: F:\\pdf\\dest.pdf * @return 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0, * 则表示操作成功; 返回1, 则表示转换失败 */ public static int office2PDF(String sourceFile, String destFile) { try { File inputFile = new File(sourceFile); if (!inputFile.exists()) { return -1;// 找不到源文件, 则返回-1 } // 如果目标路径不存在, 则新建该路径 File outputFile = new File(destFile); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } // connect to an OpenOffice.org instance running on port 8100 OpenOfficeConnection connection = new SocketOpenOfficeConnection( "127.0.0.1", 8100); connection.connect(); // convert DocumentConverter converter = new OpenOfficeDocumentConverter( connection); converter.convert(inputFile, outputFile); // close the connection connection.disconnect(); return 0; } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } catch (ConnectException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 1; }