赞
踩
OpenOffice 是 Apache 开源的一个办公组件,可以直接到官网下载使用。适用windows、linux、mac等各大平台,当然对我们程序员来说,肯定不会下载下来用用就完了。我们要在代码中使用她,实现一些 web 项目中的附件预览功能。本文只测试了Excel转PDF,稍加改动便可在线预览。
(官网下载地址,傻瓜式安装,一路点)
- <dependency>
- <groupId>org.jodconverter</groupId>
- <artifactId>jodconverter-core</artifactId>
- <version>4.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.jodconverter</groupId>
- <artifactId>jodconverter-local</artifactId>
- <version>4.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.jodconverter</groupId>
- <artifactId>jodconverter-spring-boot-starter</artifactId>
- <version>4.3.0</version>
- </dependency>
jodconverter: local: enabled : true office-home : C:\Program Files (x86)\OpenOffice 4 max-tasks-per-process : 10 port-numbers : 8100
(注意:这里的office-home路径不统一,并不是一定和安装路径在一块的,具体可以搜索一下OpenOffice这个文件在哪个位置,再深的我也搞不明白)
Controller里面引入转换器和流处理。我是在Test下测试的--这部分代码只是转EXcel转PDF,至于输出到前端页面在第二部分。
//需要转换的文件 File file = new File("E://目标源文件.xlsx"); //转换文件生成的地址 File newFile = new File("E:/test"); //判断文件是否存在 if (!newFile.exists()) { newFile.mkdirs(); } //文件转化 try { converter.convert(file).to(new File("E:/test/1.pdf")).execute(); } catch (OfficeException e) { e.printStackTrace(); }
//需要转换的文件 File file = new File("E://目标源文件.xlsx"); //转换文件生成的地址 File newFile = new File("E:/test"); //判断文件是否存在 if (!newFile.exists()) { newFile.mkdirs(); } //文件转化 try { //converter这个的类是import org.jodconverter.core.DocumentConverter converter.convert(file).to(new File("E:/test/1.pdf")).execute(); } catch (OfficeException e) { e.printStackTrace(); } //使用response将pdf以流的格式发送 ServletOutputStream outputStream = response.getOutputStream(); //读取文件 InputStream in = new FileInputStream(new File("E:/test/1.pdf")); //copy份文件 int i = IOUtils.copy(in, outputStream); in.close(); outputStream.close();
本机环境下测试成功,注意:文件的字体、格式、颜色都有保留。
六、修改乱码
本机无误后。部署到linux上后,出现转换乱码问题。解决办法安装字体。因为linux字体不如Windows的那么全,在/opt/openoffice4/program/路径下,安装:
apt-get install -y ttf-baekmuk
解决
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。