在项目中有时候需要将 Word 文件转换为 PDF
下面是我根据这几天在网上搜索的相关资料得出的总结
| 名称 | 说明 |
aspose | 该插件需要付费,功能强大支满足绝大部分业务场景持跨平台使用方便 官网地址:File Format APIs for Word Excel PDF Email PowerPoint Barcode Images OCR Note & 3D |
jacob | 未使用可参考下面地址 |
Docx4j | 该插件开源,使用起来复杂。在Word转PDF时会出现转换错误 官网地址:docx4j GitHub地址:https://github.com/plutext/docx4j |
Itext | 可以用使用 IText5 将 Word 转成 html 在由 html 转成 PDF,过程复杂且转出的 PDF不能保证格式正确 目前 IText 已经升级到 IText7 转为收费,部分插件开源 |
xdocreport | 自己找到的资源较少,通过测试发现转换PDF也会存在格式出错 GitHub地址: 文档转换说明地址:https://github.com/opensagres/xdocreport/wiki/Converters |
documents4j | 目前正在使用的方法,需要安装在 Windows 下且电脑需要安装 Office 官网地址首页有就相关 Word 转 PDF 的方法 |
下面是使用 documents4j 将 Word 转 PDF 的代码
<-- pom.xml -->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.0</version>
</dependency>
package com.converter;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
/**
* @author hjf
* @version 1.0
* @description
* @date 2022-05-25 10:39
*/
public class ConverterPDF {
/**
* 执行 Word 转 PDF
*
* @param fileName Word文档名称
* @param inDir word文件所在路径
* @param outDir pdf 文件输出路径
* @return pdf 文件路径
*/
public static String WordToPDF(String fileName, String inDir, String outDir) {
InputStream doc = null;
OutputStream pdf = null;
//构建转换器
IConverter converter = null;
// word 文件路径
String docPath = inDir + '/' + fileName + ".docx";
// pdf 文件路径
String pdfPath = outDir + '/' + fileName + ".pdf";
try {
doc = new FileInputStream(docPath);
pdf = new FileOutputStream(pdfPath);
converter = LocalConverter.builder().build();
//执行文件转换
converter.convert(doc).as(DocumentType.DOCX).to(pdf).as(DocumentType.PDF).execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭流
if (doc != null) {
doc.close();
}
if (pdf != null) {
pdf.close();
}
//关闭转换器
if (converter != null) {
converter.shutDown();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pdfPath;
}
}
本文对比了几种将Word文档转换为PDF的方法,包括aspose、jacob、Docx4j、Itext、xdocreport及documents4j。详细介绍了各方案的特点、优缺点,并提供了使用documents4j进行转换的具体代码示例。

3万+

被折叠的 条评论
为什么被折叠?



