1.下载安装 LibreOffice
https://www.libreoffice.org/download/download-libreoffice/
2.Maven 配置
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.4.8</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local-lo</artifactId>
<version>4.4.8</version>
</dependency>
3.application.properties 配置
#LibreOffice配置
jodconverter.local.enabled=true
# /usr/bin/libreoffice # Linux下的路径示例
# C:/Program Files/LibreOffice # Windows下的路径示例
jodconverter.local.office-home=C:/Program Files/LibreOffice
# 可启动多个进程处理并发
jodconverter.local.port-numbers=9080,9081,9082
# 每个进程重启前最大任务数
jodconverter.local.max-tasks-per-process=100
4.工具类
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
@Service
public class OfficeConvertService {
@Autowired
private DocumentConverter documentConverter;
/**
* Word文件转换成PDF文件
*/
public void convertWordToPdf(File wordFile, File pdfFile) {
try {
documentConverter
.convert(wordFile)
.to(pdfFile)
.execute();
} catch (Exception e) {
throw new RuntimeException("文档转换失败", e);
}
}
/**
* Word输入流转换成PDF输出流
*/
public void convertStream(InputStream inputStream, OutputStream outputStream) {
try {
documentConverter
.convert(inputStream)
.as(DefaultDocumentFormatRegistry.DOCX) // 指定源文件格式
.to(outputStream)
.as(DefaultDocumentFormatRegistry.PDF) // 指定目标格式
.execute();
} catch (Exception e) {
throw new RuntimeException("流式转换失败", e);
}
}
}