已过时,不再推荐
推荐使用 OnlyOffice 转换服务实现 word 转 PDF。基础框架中已经封装
下载并安装 office 另存 pdf 插件 SaveAsPDFandXPS.exe
https://microsoft-save-as-pdf-or-xps-add-in-for.software.informer.com/download/?lang=zh
下载 Jacob
https://github.com/freemansoft/jacob-project/releases/tag/Root_B-1_20
dll 文件
解压上面下载的文件,里面包含 dll 文件,将 jacob-1.20-x64.dll 放在 JAVA_HOME/bin 目录中
工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| package com.bjtcrj.scm.common.utils;
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant;
public class Word2Pdf { public static void translate (String wordpath, String pdfpath){ System.out.println("启动Word..."); ComThread.InitMTA(true); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", new Variant(false)); app.setProperty("AutomationSecurity", new Variant(3)); Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档 >>> " + wordpath); doc = Dispatch.call(docs, "Open", wordpath, false, true).toDispatch(); System.out.println("转换文档 [" + wordpath + "] >>> [" + pdfpath + "]"); File file = new File(pdfpath); if(file.exists()) { file.delete(); }
Dispatch.call(doc, "SaveAs", pdfpath, 17);
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", false); System.out.println("关闭文档"); if (app != null) { app.invoke("Quit", new Variant[] {}); } ComThread.Release(); ComThread.quitMainSTA(); } }
public static void main(String[] args) { translate("/Users/wangwz/Downloads/1.docx", "/Users/wangwz/Downloads/1.pdf"); }- }
|