最近帮老师做项目,实现word转pdf的功能,以前用的是openOffice这个开源的软件,但是遇到超大的doc文件就悲剧了。老师在测试的时候竟然要转100+M的文件,结果程序就崩溃了,这也说明果然微软的自己的东西还是得用自己的转换器呀。于是我就改用jacob包和word2007的转换器插件来实现超大的word转pdf,速度提升的超多,而且也不存在乱码的情况。
步骤:
1.安装office2007
2.下载office2007能另存为pdf的插件 SaveAsPDFandXPS.exe 并安装
3.下载jacob1.9
4.jacob.jar 放在 E:\jdk1.7\jre\lib\ext (ps:我这里用的是jdk1.7的版本)
jacob.dll 放在 E:\jdk1.7\jre\bin
5.导入word2pdfTest.java
资源地址:点击打开链接
package test; 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 Word2PdfTest { static final int wdFormatPDF = 17;// PDF 格式 public void wordToPDF(String sfileName,String toFileName){ System.out.println("启动Word..."); long start = System.currentTimeMillis(); 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" , sourceFile).toDispatch(); doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch(); System.out.println("打开文档..." + sfileName); System.out.println("转换文档到PDF..." + toFileName); File tofile = new File(toFileName); if (tofile.exists()) { tofile.delete(); } // Dispatch.call(doc, "SaveAs", destFile, 17); Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { toFileName, new Variant(17) }, new int[1]); long end = System.currentTimeMillis(); System.out.println("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { e.printStackTrace(); System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { Dispatch.call(doc,"Close"); System.out.println("关闭文档"); if (app != null) app.invoke("Quit", new Variant[] {}); } //如果没有这句话,winword.exe进程将不会关闭 ComThread.Release(); } public static void main(String[] args) { Word2PdfTest d = new Word2PdfTest(); d.wordToPDF("C:\\Users\\lhq\\Desktop\\Z01_0001.doc", "C:\\Users\\lhq\\Desktop\\Z01_0001.pdf"); } }