使用 docx4j 实现 DOCX 转 PDF,核心是通过 XSL-FO + Apache FOP 进行格式转换。以下是完整、可直接运行的方案(Maven + Java)。
一、核心依赖(Maven)
需引入 docx4j-core 和 PDF 导出模块 docx4j-export-fo:
<dependencies>
<!-- docx4j 核心库 -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-core</artifactId>
<version>11.5.4</version>
</dependency>
<!-- FO 导出(转PDF必需) -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>11.5.4</version>
</dependency>
<!-- JAXB 实现(JDK 9+ 必须显式引入) -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>11.5.4</version>
</dependency>
</dependencies>
二、最简转换代码(含中文支持)
import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class DocxToPdfConverter {
public static void convert(String docxPath, String pdfPath) throws Exception {
// 1. 加载 DOCX 文件
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(new File(docxPath));
// 2. 配置字体映射(解决中文乱码/方框问题)
Mapper fontMapper = new IdentityPlusMapper();
// 自动扫描系统字体
PhysicalFonts.discoverPhysicalFonts();
// 常用中文字体映射(Windows/Linux通用)
fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft YaHei"));
fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
pkg.setFontMapper(fontMapper);
// 3. 转换并输出 PDF
try (OutputStream os = new FileOutputStream(pdfPath)) {
// FLAG_EXPORT_PREFER_XSL:兼容性最好
Docx4J.toPDF(pkg, os);
}
}
// 测试
public static void main(String[] args) throws Exception {
convert("input.docx", "output.pdf");
System.out.println("转换完成");
}
}
三、测试结果
- 原始文档
- 转换效果
四、结论
- 格式兼容性问题比较多,简单文档可以使用,兼容性要求高的情况下,建议放弃
- 由于不能预知要转换的文档中使用了哪些中文字体,可能出现###,这个问题比较严重