下面给你一个在 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(最常用、免费)
1️⃣ 原理
Spring Boot 调用服务器上的 soffice命令将 .docx→ .pdf
2️⃣ 安装 LibreOffice
bash
# Ubuntu
sudo apt install libreoffice
# CentOS
yum install libreoffice
# Windows
下载安装 LibreOffice
3️⃣ Spring Boot 示例代码
Maven 依赖(无需额外)
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
Service 示例
arduino
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(企业级)
1️⃣ Maven 依赖
xml
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>11.4.9</version>
</dependency>
<dependency>
<groupId>org.plutext</groupId>
<artifactId>plutext-pdf-converter</artifactId>
<version>3.3.0</version>
</dependency>
2️⃣ 转换代码
java
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
xml
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>23.12</version>
</dependency>
代码示例
ini
import com.aspose.words.Document;
Document doc = new Document("input.docx");
doc.save("output.pdf");
✅ 转换效果最好
❌ 商业授权昂贵
五、常见问题 & 解决方案
✅ 中文乱码
-
Linux 安装中文字体
yum install wqy-microhei-fonts
✅ 并发问题
- LibreOffice 不建议多线程同时转换
- 可使用线程池 + 队列
✅ Web 接口示例
swift
@PostMapping("/convert")
public ResponseEntity<?> convert(MultipartFile file) throws Exception {
// 保存word
// 调用转换
// 返回pdf流
}
六、推荐选型总结
| 场景 | 推荐方案 |
|---|---|
| 普通后台系统 | LibreOffice |
| 企业文档系统 | docx4j + Plutext |
| 金融/合同/报表 | Aspose.Words |
如果你愿意,我可以:
- ✅ 给你写一个 完整的 Spring Boot Demo
- ✅ 封装成 工具类
- ✅ 处理 Word 模板 → PDF
- ✅ 解决 Linux 中文乱码
你可以直接告诉我:你的部署环境 + 是否有预算 + 是否要模板。