300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Java实现OpenOffice将word转换为pdf

Java实现OpenOffice将word转换为pdf

时间:2019-09-20 05:52:54

相关推荐

Java实现OpenOffice将word转换为pdf

1、因项目需求,使用openoffice+jodconverter,在服务器端将word转换为pdf。本案例是一种解决方法,但不是最好的解决方法,因为服务端需要安装openoffice软件,依赖的jodconverter jar版本2.2.1比较老,不支持office07以后的版本,而2.2.2版本在中央仓库没有。所以,后续可采用其他解决方法。

2、maven依赖

<dependency><groupId>com.artofsolving</groupId><artifactId>jodconverter</artifactId><version>2.2.1</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>jurt</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>ridl</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>juh</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>unoil</artifactId><version>3.0.1</version></dependency><!--jodconverter2.2.1必须依赖slf4j-jdk14必须这个版本,不然源码中日志会报错--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-jdk14</artifactId><version>1.4.3</version></dependency>

3、第一次安装好openoffice的时候,记得打开openoffice,根据要求进行用户名、公司名称输入注册,否则后面转换的时候报错,连接失败。

4、转换实现

// 将word格式的文件转换为pdf格式public void Word2Pdf(String srcPath, String desPath) {OpenOfficeConnection connection = null;Process p = null;try {// 源文件目录File inputFile = new File(srcPath);if (!inputFile.exists()) {System.out.println("源文件不存在!");return;}// 输出文件目录File outputFile = new File(desPath);if (!outputFile.getParentFile().exists()) {outputFile.getParentFile().exists();}// 调用openoffice服务线程String command = "C:\\Program Files (x86)\\OpenOffice 4\\program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";p = Runtime.getRuntime().exec(command);// 连接openoffice服务connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);connection.connect();// 转换word到pdfDocumentConverter converter = new OpenOfficeDocumentConverter(connection);converter.convert(inputFile, outputFile);System.out.println("转换完成!");} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {// 关闭连接connection.disconnect();}if (p != null) {// 关闭进程p.destroy();}}

其中,记得在finally将连接和进程关闭,否则如果转换过程中出异常,程序终止后,进程和连接可能还在运行。

5、测试

@Testpublic void testWord2Pdf() throws IOException {String srcPath = "D:/test.doc";String desPath = "D:/test.pdf";Word2Pdf(srcPath, desPath);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。