开发过程中需求提出导出的文档应当为pdf格式,而前期需求已经做了导出docx文档,故需要在此前的基础上将docx转为pdf后再给用户下载。
docx文档通过Apache POI生成,本文主要分享转换pdf的方法poi相关就不谈了。
注意:开发环境与部署环境均为Windows平台!
转换pdf利用WPS完成,因此需要在开发或部署环境安装WPS。(MS Office也支持,但在代码中略有区别)
首先需要准备jacob,它是用于Java程序与系统沟通的桥梁。可以在github下载官方发行版,也可以点击这里可以下载我准备好的,下载完成后解压放在任意目录(例如我将其放在C盘根目录下,即“C:\jacob”路径)。
其文件夹中包含三个文件,分别是
- jacob-1.21-x64.dll
- jacob-1.21-x86.dll
- jacob.jar
将jacob.jar导入到项目lib目录并添加依赖
创建工具类WordToPdfConverter.java
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.io.File;
public class WordToPdfConverter {
// 此处路径要填写刚才说的jacob解压后放的路径,依据电脑的64或32位架构选择对应的dll
static {
System.setProperty("jacob.dll.path", "C:\\jacob\\jacob-1.21-x64.dll");
}
// 枚举类定义 Word 文件格式
enum FileFormatEnum {
wdFormatPDF(17); // PDF 格式
private final int value;
FileFormatEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
// 入参为完整的docx路径,例如C:\export\abc.docx
public static void convertDocxToPdfAndDelete(String docxFilePath) {
try {
File docxFile = new File(docxFilePath);
if (!docxFile.exists()) {
System.out.println("指定的 .docx 文件不存在!");
return;
}
String pdfFilePath = docxFilePath.replace(".docx", ".pdf");
// 如果使用WPS实现则此处填写KWPS.Application
// 如果使用MS Office实现则此处填写Word.Application
ActiveXComponent wps = new ActiveXComponent("KWPS.Application");
wps.setProperty("Visible", new Variant(false));
Dispatch documents = wps.getProperty("Documents").toDispatch();
Dispatch document = Dispatch.call(documents, "Open",
docxFilePath,
new Variant(false),
new Variant(true)
).toDispatch();
FileFormatEnum fileFormat = FileFormatEnum.wdFormatPDF;
Dispatch.call(document, "SaveAs",
pdfFilePath,
new Variant(fileFormat.getValue())
);
Dispatch.call(document, "Close", new Variant(false));
wps.invoke("Quit");
File pdfFile = new File(pdfFilePath);
if (pdfFile.exists()) {
System.out.println("文件转换成功!PDF 文件已保存到:" + pdfFilePath);
docxFile.delete();
} else {
System.out.println("PDF 文件生成失败,未删除原始 .docx 文件。");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("文件转换过程中发生错误,未删除原始 .docx 文件。");
}
}
}
然后从需要的地方调用即可。
在查找这个方案之前还被wps的文档给误导了,wps的官方文档说支持命令行wps -convert-to pdf -o "输出文件夹路径" "输入文件夹路径*.wps"
调用,但是实际测试了半天根本不行。
希望文章能帮到你。