说明:使用本方法计算机中必须含有office
一.准备工作
1.准备如图三个文件:
2.将第二个文件复制到C:\Windows\System32,将第三个文件复制到C:\Windows\SysWOW64,
然后将这两个文件复制到jdk,jre里面的bin文件夹
二.开始编译
1.项目导入第一个文件的jar包
2.代码如图所示:
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import java.io.File; public class Test { static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。 static final int wdFormatPDF = 17;// PDF 格式 public static void wordToPdf(String wordpath, String pdfpath) { System.out.println("启动Word..."); long start = System.currentTimeMillis(); ActiveXComponent app = null; try { //打开word应用程序 app = new ActiveXComponent("Word.Application"); ////设置应用操作是文档不在明面上显示,只在后台静默处理。 app.setProperty("Visible", false); //获得文档集合,用来操作我们需要处理的文档. Dispatch docs = app.getProperty("Documents").toDispatch(); System.out.println("打开文档..." + wordpath); //打开word文档 Dispatch doc = Dispatch.call(docs,// "Open", // wordpath,// FileName false,// ConfirmConversions true // ReadOnly ).toDispatch(); System.out.println("转换文档到PDF..." + pdfpath); File tofile = new File(pdfpath); //创建存放pdf的文件夹 if (tofile.exists()) { tofile.delete(); } //将word另存为pdf Dispatch.call(doc,// "SaveAs", // pdfpath, // FileName wdFormatPDF); //关闭word文档 Dispatch.call(doc, "Close", false); long end = System.currentTimeMillis(); System.out.println("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { if (app != null) app.invoke("Quit", wdDoNotSaveChanges); } } public static void main(String[] args) { wordToPdf("C:\\Users\\wukefan\\Desktop\\test.doc","C:\\Users\\wukefan\\Desktop\\test.pdf"); } }
三.运行项目
1.运行成功,项目结果如图所示:
2.如图所示桌面,桌面多了个pdf文件: