下面给你一个在 Spring Boot 中实现 Word 转 PDF 的完整思路与示例,覆盖主流可行方案、推荐做法以及注意事项,你可以按项目需求选择。
一、总体方案对比
| 方案 | 是否收费 | 转换质量 | 依赖环境 | 推荐指数 |
|---|---|---|---|---|
| docx4j + Plutext PDF Converter | 商业需授权 | ⭐⭐⭐⭐⭐ | 无(Java) | ✅✅✅ |
| LibreOffice(命令行) | 免费 | ⭐⭐⭐⭐ | 需安装LibreOffice | ✅✅✅ |
| Apache POI + iText(间接) | 免费 | ⭐⭐ | 复杂 | ❌ |
| Aspose.Words for Java | 商业 | ⭐⭐⭐⭐⭐ | 无 | ✅(有钱) |
生产环境最推荐:
- Windows/Linux 服务器:LibreOffice
- 企业级高质量:docx4j + Plutext(或 Aspose)
二、方案一:LibreOffice(最常用、免费)
原理
Spring Boot 调用服务器上的 soffice命令将 .docx→ .pdf
安装 LibreOffice
# Ubuntu sudo apt install libreoffice # CentOS yum install libreoffice # Windows 下载安装 LibreOffice
Spring Boot 示例代码
Maven 依赖(无需额外)
org.springframework.bootspring-boot-starter
Service 示例
import java.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 必须安装字体(否则中文乱码)
- 不支持并发过高(建议队列或限制线程)
三、方案二:docx4j + Plutext(企业级)
Maven 依赖
org.docx4jdocx4j11.4.9org.plutextplutext-pdf-converter3.3.0
转换代码
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import java.io.FileOutputStream;
public void convert() throws Exception {
WordprocessingMLPackage wordMLPackage =
WordprocessingMLPackage.load(new File("input.docx"));
Docx4J.toPDF(wordMLPackage, new FileOutputStream("output.pdf"));
}
优点
- 纯 Java
- 不依赖外部软件
- 样式还原好
缺点
- Plutext 商用需授权
- 对复杂表格/页眉页脚偶有偏差
四、方案三:Aspose.Words(最强但贵)
Maven
com.asposeaspose-words23.12
代码示例
import com.aspose.words.Document;
Document doc = new Document("input.docx");
doc.save("output.pdf");
五、常见问题 & 解决方案
中文乱码
Linux 安装中文字体
yum install wqy-microhei-fonts
并发问题
- LibreOffice 不建议多线程同时转换
- 可使用线程池 + 队列
Web 接口示例
@PostMapping("/convert")
public ResponseEntity> convert(MultipartFile file) throws Exception {
// 保存word
// 调用转换
// 返回pdf流
}
六、推荐选型总结
| 场景 | 推荐方案 |
|---|---|
| 普通后台系统 | LibreOffice |
| 企业文档系统 | docx4j + Plutext |
| 金融/合同/报表 | Aspose.Words |
到此这篇关于SpringBoot实现Word转PDF的完整思路与示例代码详解的文章就介绍到这了,更多相关SpringBoot Word转PDF内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
