源代码如下:
package com; 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 Test { 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", sfileName).toDispatch(); System.out.println("打开文档..." + sfileName); System.out.println("转换文档到PDF..." + toFileName); File tofile = new File(toFileName); if (tofile.exists()) { tofile.delete(); } Dispatch.call(doc, "SaveAs", toFileName, // FileName wdFormatPDF); long end = System.currentTimeMillis(); System.out.println("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { Dispatch.call(doc, "Close", false); System.out.println("关闭文档"); if (app != null) app.invoke("Quit", new Variant[] {}); } // 如果没有这句话,winword.exe进程将不会关闭 ComThread.Release(); } public static void main(String[] args) { Test d = new Test(); d.wordToPDF("E:\\合同文本2014.doc", "E:\\合同文本2014.pdf"); } }
package com; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class TransformFiletoHtml { public static void wordToPDF(String docfile, String toFile) { ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word try { app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] { docfile, new Variant(false), new Variant(true) }, new int[1]).toDispatch(); // new Variant(type),这里面的type的决定另存为什么类型的文件 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { toFile, new Variant(17) }, new int[1]); //Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { toFile }, new int[17]); Variant f = new Variant(false); Dispatch.call(doc, "Close", f); } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); } } public static void main(String[] args) { // 源文件全路径 String docfile = "D:\\合同文本2014.doc"; // 些路径test为实际存在的目录,s后面为要另存为的文件名 String toFile = "D:\\合同文本2014.pdf"; wordToPDF(docfile, toFile); } }