在企业级应用开发中,经常需要将Word文档(.doc 或 .docx)转换为PDF格式,以便于打印、归档或安全分发。本文介绍几种主流的Java实现方案。
Free Spire.Doc 是一个功能强大的商业库,提供免费版本(有页数限制),支持高质量 Word 转 PDF。
// Maven依赖(免费版)
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
// Java代码示例
import com.spire.doc.*;
public class WordToPdf {
public static void main(String[] args) {
Document doc = new Document();
doc.loadFromFile("input.docx");
doc.saveToFile("output.pdf", FileFormat.PDF);
}
}
Apache POI 可读取 Word 内容,iText 可生成 PDF,但需手动处理格式映射,适合简单文档。
通过调用本地安装的 LibreOffice 实现转换,适合服务器环境。
// 需先安装 LibreOffice
// Java调用命令行或使用 JODConverter 库
String command = "soffice --headless --convert-to pdf input.docx";
Runtime.getRuntime().exec(command);