Java Springboot 使用 OpenOffice 实现Excel转PDF

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

一、OpenOffice安装

Apache OpenOffice - Official Download

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

二、Pom依赖

<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>

三、配置文件 application-dev.yml

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

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

四、代码(EXcel转PDF)

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();
}

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

//需要转换的文件
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

解决 

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值