两种主流方案详解 | 完整代码示例 | 生产环境可用
摘要:在企业应用开发中,经常需要将Word文档转换为PDF格式以确保内容的不可篡改性和跨平台一致性。本文将介绍两种在Java中高效、不失真地实现Word转PDF的方法,并提供完整的可运行代码。
Java作为企业级应用开发的主流语言,在文档处理方面有着成熟的解决方案。通过Java程序自动化转换Word到PDF,可以:
此方法适用于简单的.docx文档转换,依赖纯Java库,部署简单。
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.15</version>
<type>pom</type>
</dependency>
</dependencies>
import org.apache.poi.xwpf.usermodel.*;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class WordToPdfConverter {
public static void convert(String wordPath, String pdfPath) throws Exception {
// 读取Word文档
XWPFDocument document = new XWPFDocument(new FileInputStream(wordPath));
// 创建PDF写入器
PdfWriter writer = new PdfWriter(pdfPath);
com.itextpdf.kernel.pdf.PdfDocument pdfDoc = new com.itextpdf.kernel.pdf.PdfDocument(writer);
Document pdfDocument = new Document(pdfDoc);
// 遍历Word段落并写入PDF
for (XWPFParagraph paragraph : document.getParagraphs()) {
String text = paragraph.getText();
if (text != null && !text.trim().isEmpty()) {
pdfDocument.add(new Paragraph(text));
}
}
// 关闭资源
pdfDocument.close();
document.close();
}
public static void main(String[] args) {
try {
convert("input.docx", "output.pdf");
System.out.println("转换完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
利用LibreOffice强大的文档渲染引擎,通过命令行调用实现高质量的Word到PDF转换,几乎完美保留原始格式。
在服务器上安装 LibreOffice
import java.io.File;
public class LibreOfficeConverter {
/**
* 使用LibreOffice将Word文档转换为PDF
* @param inputWordPath 输入的Word文件路径
* @param outputPdfPath 输出的PDF文件路径
* @return 转换是否成功
*/
public static boolean convertToPdf(String inputWordPath, String outputPdfPath) {
try {
File inputFile = new File(inputWordPath);
File outputFile = new File(outputPdfPath);
// 确保输入文件存在
if (!inputFile.exists()) {
System.err.println("输入文件不存在: " + inputWordPath);
return false;
}
// 构建命令
String command;
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// Windows系统
command = "soffice --headless --convert-to pdf --outdir \""
+ outputFile.getParent() + "\" \"" + inputWordPath + "\"";
} else {
// Linux/Mac系统
command = "libreoffice --headless --convert-to pdf --outdir \""
+ outputFile.getParent() + "\" \"" + inputWordPath + "\"";
}
// 执行命令
Process process = Runtime.getRuntime().exec(command);
int exitCode = process.waitFor();
// 检查输出文件
File generatedPdf = new File(outputFile.getParent(),
inputFile.getName().replaceFirst("\\.[^.]+$", "") + ".pdf");
return exitCode == 0 && generatedPdf.exists();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
boolean success = convertToPdf("example.docx", "result.pdf");
System.out.println("转换" + (success ? "成功" : "失败"));
}
}
方案 | 转换质量 | 部署复杂度 | 适用场景 |
---|---|---|---|
Apache POI + iText | ★☆☆☆☆ | 低(纯Java) | 简单文本文档,轻量级应用 |
LibreOffice调用 | ★★★★★ | 中(需安装软件) | 正式生产环境,要求高保真 |