####前言:最近作一个项目,须要一个word转化为pdf的功能,因而本身经过在网上找各类资料。测试了好几个方法,最后决定使用jacob(Java COM Bridge)操做office的方式,主要的缘由是这边word文件涉及到的内容和样式比较复杂,若是使用其余方法,例如docx4j不可以很好的处理(也多是我没有深刻研究的缘由)。网上虽然已经有不少相似的教程了,有些说的很详细,可是有些说的确并不太清楚,本身结合其余文章总结一下
####一、下载相关的jar包和dll文件
放在了云盘里面,免费给你们下载
连接: https://pan.baidu.com/s/1nvutQxb 密码: qgpi
####二、引入jar文件和dll文件
jar文件的引入就很少说了,关于dll文件,放在jdk文件下面的bin目录下
####三、具体代码java
package transform; import java.io.File; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; public class Word2Pdf { public static void main(String args[]) { ActiveXComponent app = null; String wordFile = "e:/我的成长规划报告.doc"; String pdfFile = "e:/我的成长规划报告.pdf"; System.out.println("开始转换..."); // 开始时间 long start = System.currentTimeMillis(); try { // 打开word app = new ActiveXComponent("Word.Application"); // 设置word不可见,不少博客下面这里都写了这一句话,实际上是没有必要的,由于默认就是不可见的,若是设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的 //app.setProperty("Visible", false); // 得到word中全部打开的文档 Dispatch documents = app.getProperty("Documents").toDispatch(); System.out.println("打开文件: " + wordFile); // 打开文档 Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch(); // 若是文件存在的话,不会覆盖,会直接报错,因此咱们须要判断文件是否存在 File target = new File(pdfFile); if (target.exists()) { target.delete(); } System.out.println("另存为: " + pdfFile); // 另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17 Dispatch.call(document, "SaveAs", pdfFile, 17); // 关闭文档 Dispatch.call(document, "Close", false); // 结束时间 long end = System.currentTimeMillis(); System.out.println("转换成功,用时:" + (end - start) + "ms"); }catch(Exception e) { System.out.println("转换失败"+e.getMessage()); }finally { // 关闭office app.invoke("Quit", 0); } } }
后续须要的话,会继续对jacob进行深刻研究web