基于Jacob+SaveAsPDFandXPS+MicrosoftOfficeWord实现word转pdf
优点:功能强大,转换效果好,支持格式全
缺点:转换速度慢,只支持windows环境,需要有office软件,以及需要加装插件
Jacob:JACOB一个Java-COM中间件,通过这个组件你可以在Java应用程序中调用COM组件和Win32程序库。
SaveAsPDFandXPS:SaveAsPDFandXPS是微软官方出品,免费且小巧,可直接将word文档(docx/doc)保存为pdf或者xps。
本套方案中,所有匹配文件的下载地址:Jacob+SaveAsPdfAndXps
包含内容:
具体实现:
第一步:安装SaveAsPDFandXPS插件
第二步:把dll文件放到jre的bin目录下
电脑是64位的就用x64的,32位的就用x86的
第三步:引入jar包
java项目直接引入;
maven项目引入代码(jacob包在阿里maven仓库中没有,要用中央仓库的地址:https://mvnrepository.com/)
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.10</version>
</dependency>
第四步:书写代码
package com.jacob.word2pdf;
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordToPdf {
private static final int wdFormatPDF = 17;// PDF 格式
/**
* word转pdf 支持doc, docx
* @param inputFile 转换前的文件路径
* @param pdfFile 转换后的文件路劲
*/
public static void wordToPDF(String startFile, String overFile){
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open" , startFile).toDispatch();
File tofile = new File(overFile);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", overFile, wdFormatPDF);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//结束后关闭进程
ComThread.Release();
}
/**
* 根据传入文件将word转为pdf
* @param wordFile
* @return
*/
public static File wordToPDFByFile(File wordFile){
File returnFile = null;
try {
String inputFilePath = wordFile.getAbsolutePath();
System.out.println("生成传入临时文件路径: "+inputFilePath);
String pdfFilePath = inputFilePath.substring(0,inputFilePath.lastIndexOf("."))+1 + "pdf";
System.out.println("生成pdf文件路径: "+pdfFilePath);
wordToPDF(inputFilePath, pdfFilePath);
returnFile = new File(pdfFilePath);
} catch (Exception e) {
e.printStackTrace();
}
return returnFile;
}
public static void main(String[] args) {
String path = "C://Users//zrc//Desktop//新建 DOCX 文档.docx";
String newPath = "C://Users//zrc//Desktop//新建 DOCX 文档.pdf";
wordToPDF(path,newPath);
// String path = "C://Users//zrc//Desktop//新建 DOCX 文档.docx";
// File file = new File(path);
// File pdf = wordToPDFByFile(file);
}
}
亲测有效!!!