当前位置:   article > 正文

Java Springboot 使用 OpenOffice 实现Excel转PDF_spring-boot-starter-openoffice

spring-boot-starter-openoffice

OpenOffice 是 Apache 开源的一个办公组件,可以直接到官网下载使用。适用windows、linux、mac等各大平台,当然对我们程序员来说,肯定不会下载下来用用就完了。我们要在代码中使用她,实现一些 web 项目中的附件预览功能。本文只测试了Excel转PDF,稍加改动便可在线预览。

一、OpenOffice安装

Apache OpenOffice - Official Download

(官网下载地址,傻瓜式安装,一路点)

二、Pom依赖

  1. <dependency>
  2. <groupId>org.jodconverter</groupId>
  3. <artifactId>jodconverter-core</artifactId>
  4. <version>4.3.0</version>
  5. </dependency>
  1. <dependency>
  2. <groupId>org.jodconverter</groupId>
  3. <artifactId>jodconverter-local</artifactId>
  4. <version>4.3.0</version>
  5. </dependency>

  1. <dependency>
  2. <groupId>org.jodconverter</groupId>
  3. <artifactId>jodconverter-spring-boot-starter</artifactId>
  4. <version>4.3.0</version>
  5. </dependency>

三、配置文件 application-dev.yml

  1. jodconverter:
  2. local:
  3. enabled : true
  4. office-home : C:\Program Files (x86)\OpenOffice 4
  5. max-tasks-per-process : 10
  6. port-numbers : 8100

 (注意:这里的office-home路径不统一,并不是一定和安装路径在一块的,具体可以搜索一下OpenOffice这个文件在哪个位置,再深的我也搞不明白)

四、代码(EXcel转PDF)

Controller里面引入转换器和流处理。我是在Test下测试的--这部分代码只是转EXcel转PDF,至于输出到前端页面在第二部分。

  1. //需要转换的文件
  2. File file = new File("E://目标源文件.xlsx");
  3. //转换文件生成的地址
  4. File newFile = new File("E:/test");
  5. //判断文件是否存在
  6. if (!newFile.exists()) {
  7. newFile.mkdirs();
  8. }
  9. //文件转化
  10. try {
  11. converter.convert(file).to(new File("E:/test/1.pdf")).execute();
  12. } catch (OfficeException e) {
  13. e.printStackTrace();
  14. }

五、代码(PDF输出到前端)

  1. //需要转换的文件
  2. File file = new File("E://目标源文件.xlsx");
  3. //转换文件生成的地址
  4. File newFile = new File("E:/test");
  5. //判断文件是否存在
  6. if (!newFile.exists()) {
  7. newFile.mkdirs();
  8. }
  9. //文件转化
  10. try {
  11. //converter这个的类是import org.jodconverter.core.DocumentConverter
  12. converter.convert(file).to(new File("E:/test/1.pdf")).execute();
  13. } catch (OfficeException e) {
  14. e.printStackTrace();
  15. }
  16. //使用response将pdf以流的格式发送
  17. ServletOutputStream outputStream = response.getOutputStream();
  18. //读取文件
  19. InputStream in = new FileInputStream(new File("E:/test/1.pdf"));
  20. //copy份文件
  21. int i = IOUtils.copy(in, outputStream);
  22. in.close();
  23. outputStream.close();

本机环境下测试成功,注意:文件的字体、格式、颜色都有保留。 

六、修改乱码

本机无误后。部署到linux上后,出现转换乱码问题。解决办法安装字体。因为linux字体不如Windows的那么全,在/opt/openoffice4/program/路径下,安装:

apt-get install -y ttf-baekmuk

解决 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/825760
推荐阅读
相关标签
  

闽ICP备14008679号