发布于2026-07-07 阅读(0)
扫一扫,手机访问
先说结论:在 Spring Boot 项目里做 Word 转 PDF,其实路数就那么几条。选哪个方案,主要看你的场景——是追求免费快速搞定,还是要求格式还原度拉满。下面直接上干货。

先把市面上主流的选择摆出来,哪个适合你,看这张表心里就有数了。
| 方案 | 是否收费 | 转换质量 | 依赖环境 | 推荐指数 |
|---|---|---|---|---|
| docx4j + Plutext PDF Converter | 商业需授权 | ⭐⭐⭐⭐⭐ | 无(纯Ja va) | ✅✅✅ |
| LibreOffice(命令行) | 免费 | ⭐⭐⭐⭐ | 需安装LibreOffice | ✅✅✅ |
| Apache POI + iText(间接) | 免费 | ⭐⭐ | 复杂 | ❌ |
| Aspose.Words for Ja va | 商业 | ⭐⭐⭐⭐⭐ | 无 | ✅(预算充足可上) |
生产环境到底选哪个?其实结论很明确:如果服务器是Windows或Linux,LibreOffice几乎是最顺手的选择;如果对转换质量要求极高,企业级应用直接走docx4j加Plutext或Aspose。
说白了,就是Spring Boot在后台调一下服务器上的 soffice 命令,把 .docx 扔进去,让它帮你转成 .pdf,简单粗暴。
# Ubuntu sudo apt install libreoffice # CentOS yum install libreoffice # Windows 直接下载安装包搞定
Ma ven 依赖,这个不需要额外加什么库,基础 starter 就够了:
org.springframework.boot spring-boot-starter
Service 长这样:
import ja va.io.*;
@Service
public class WordToPdfService {
public void convert(String wordPath, String pdfPath) throws Exception {
String command = "libreoffice --headless --convert-to pdf "
+ wordPath + " --outdir " + new File(pdfPath).getParent();
Process process = Runtime.getRuntime().exec(command);
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Word转PDF失败");
}
}
}
这个方案的好处显而易见:免费,支持 .doc 和 .docx,格式还原度也相当能打。
不过有几个坑值得注意。Linux上必须装中文字体,不然输出全是乱码。另外,LibreOffice不太适合高并发场景,建议加个线程池或队列来排队执行。
org.docx4j docx4j 11.4.9 org.plutext plutext-pdf-converter 3.3.0
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import ja va.io.FileOutputStream;
public void convert() throws Exception {
WordprocessingMLPackage wordMLPackage =
WordprocessingMLPackage.load(new File("input.docx"));
Docx4J.toPDF(wordMLPackage, new FileOutputStream("output.pdf"));
}
这套方案的好处是纯Ja va实现,不需要在服务器上安装任何第三方软件,样式的还原度也很优秀。
但有两件事你得清楚:第一,Plutext的PDF转换器在商业用途上需要授权;第二,遇到特别复杂的表格或者奇奇怪怪的页眉页脚,偶尔还是会出点小偏差。
com.aspose aspose-words 23.12
import com.aspose.words.Document;
Document doc = new Document("input.docx");
doc.sa ve("output.pdf");
这个方案几乎就是Word转PDF的“天花板”了。代码精简到只有两行,转换效果几乎没有对手。缺点也明摆着:贵。
Linux下乱码是高频问题,解决方案就是安装中文字体:
yum install wqy-microhei-fonts
LibreOffice本身不支持多线程并发转换。如果你同时来的请求太多,最好用线程池加队列的方式,把请求排好队一个一个处理。
@PostMapping("/convert")
public ResponseEntity> convert(MultipartFile file) throws Exception {
// 先把前端传的Word存到本地
// 调用转换逻辑
// 返回PDF文件流
}
把前面说的整理一下,不同场景选不同方案就行:
| 场景 | 推荐方案 |
|---|---|
| 普通后台系统 | LibreOffice |
| 企业文档系统 | docx4j + Plutext |
| 金融/合同/报表 | Aspose.Words |
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8