前言:最近在工作中遇到了一个需求要实现word转pdf,本来我在上一个公司使用aspose.words工具使用的得心应手,都已经把功能点实现了,两句代码轻轻松松,但是被告知不能用商业版的东西,公司要求只能用开源的,那么只有另想办法,想过通过word转图片再转pdf但是实现出来的效果没有想象中那么好,果断放弃,最终斟酌了一下用了libreoffice,那么下面为大家分享一下;
一丶安装Libreoffice
- 确保在服务器或运行环境中已安装 LibreOffice。
- 可以从 LibreOffice 官方网站 下载并安装。
使用国内镜像下载更快; 主页 | LibreOffice 简体中文官方网站 - 自由免费的办公套件
二丶配置 LibreOffice 为服务模式
- LibreOffice 可以以无头模式运行,处理转换任务。
- 通常,您可以通过命令行启动 LibreOffice 服务:
#这个将在后台运行Libreoffice,并监听端口2022
soffice --headless --accept="socket,host=127.0.0.1,port=2002;urp;" --nofirststartwizard &
三丶添加maven配置
#添加这两个就行
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.4.2</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.4.2</version>
</dependency>
五丶实现代码
package cn.it.resource.util;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import java.io.File;
public class JODConverterExample {
public static void main(String[] args) {
// 启动 LibreOffice 管理器
LocalOfficeManager officeManager = null;
try {
officeManager = LocalOfficeManager.builder()
.portNumbers(2002) // 与启动 LibreOffice 时的端口一致
.install()
.build();
officeManager.start();
File inputFile = new File("D:/home/server/886bdac8cf.docx"); // 替换为实际路径
File outputFile = new File("D:/home/server/wordTopdf2.pdf"); // 替换为实际路径
LocalConverter.builder()
.officeManager(officeManager)
.build()
.convert(inputFile)
.to(outputFile)
.execute();
System.out.println("文件转换成功!");
} catch (OfficeException e) {
e.printStackTrace();
} finally {
if (officeManager != null) {
try {
officeManager.stop();
} catch (OfficeException e) {
e.printStackTrace();
}
}
}
}
}
六丶出现报错异常,并解决
Exception in thread "main" java.lang.NullPointerException: officeHome must not be null
at org.jodconverter.core.util.AssertUtils.notNull(AssertUtils.java:131)
at org.jodconverter.local.office.LocalOfficeUtils.validateOfficeHome(LocalOfficeUtils.java:352)
at org.jodconverter.local.office.LocalOfficeManager$Builder.build(LocalOfficeManager.java:189)
at cn.it.resource.util.JODConverterExample.main(JODConverterExample.java:19)
启动第五步代码的时候出现了上述错误,通过检查后发现没有配置libreoffice的安装路径,我尝试了在环境变量中直接配置路径,没有用,只有自己定义实现路径;
// 必须指定安装路径 否则会报:officeHome must not be null
String officeHome = "D:/libreoffice";
// 启动 LibreOffice 管理器
LocalOfficeManager officeManager = null;
try {
officeManager = LocalOfficeManager.builder()
.portNumbers(2002) // 与启动 LibreOffice 时的端口一致
.officeHome(officeHome)
.install()
.build();
好了我的分享就在这里了,如果需要上linux服务器操作,在网上找下命令安装一下就行了,然后将代码中的安装路径修改,然后就可以使用了;