一、优缺点
优点:转换不失真,不受到中文、图片、附件影响,转换速度尚可(大约1M5秒)
缺点:Windows平台,且需要在JDK bin路径下增加 jacob.dll,并安装 Microsoft Office
二、包依赖
1、pom.xml
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
</dependency>
2、导入包
自建仓库如果有这个包,直接导入就可以了,但如果没有相关包,只能自己下载、解压、移入本地库了
(1)访问官网,并下载链接
解压后包结构如下:
(2)重命名 jacob.jar 为 jacob-1.19.jar,放到 Maven仓库
(如C:/Users/zhangsan/.m2/repository/com/jacob/jacob/1.19/)
3、将 jacob-1.19-x64.dll 或 jacob-1.19-x86.dll 放到 JDK bin 路径下
(如C:/Program Files/Java/jdk1.8.0_152/bin)
三、Java实现
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import java.io.File;
public class JacobUtil {
/**
* Word 文档转 PDF 文档
*
* @param wordPath Word 文档路径,含文件名和后缀.docx
* @param pdfPath PDF 文档路径,含文件名和后缀.pdf
* @return
* @require JDK/bin 路径下要 有jacob-*.**-x64.dll
*/
public static boolean word2Pdf(String wordPath, String pdfPath) {
ActiveXComponent app = null;
try {
File pdfFile = new File(pdfPath);
if (pdfFile.exists()) {
pdfFile.delete();
}
app = new ActiveXComponent("Word.Application");//Microsoft Office Word应用
app.setProperty("Visible", false);
Dispatch documents = app.getProperty("Documents").toDispatch();//Word内的文档
Dispatch document = Dispatch.call(documents, "Open", wordPath, false, true).toDispatch();
Dispatch.call(document, "SaveAs", pdfPath, 17);// Word → PDF 方式:值17
Dispatch.call(document, "Close", false);
if (pdfFile.exists()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (null != app) {
app.invoke("Quit", 0);
}
}
}
}
四、报错
com.jacob.com.ComFailException: Can't get object clsid from progid
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at *.utils.JacobUtil.word2Pdf(JacobUtil.java:24)
报错行是:
app = new ActiveXComponent("Word.Application");//Microsoft Office Word应用
报错原因:未安装 Microsoft Office Word应用
附:Microsoft Office 2013专业增强版 下载地址