04月 23 问题记录 文档转换文件格式 发表于 2019-04-23 • 分类于 问题记录 Word 转 PDF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748/** * word 转 pdf * * @param word * @param pdf * @return */public static boolean word2pdf(String word, String pdf) { ActiveXComponent wps = null; Dispatch doc = null; // word 保存为 pdf 格式宏,值为 17 int fmt = 17; long start = System.currentTimeMillis(); try { /** * 参数为 Word.Application:需要安装 Office * 参数为 kwps.application:需要安装 WPS * doc 转 pdf 时,用 Word.Application 报错 */ wps = new ActiveXComponent("kwps.application"); wps.setProperty("visible", new Variant(false)); Dispatch docs = wps.getProperty("Documents").toDispatch();// doc = Dispatch.invoke(docs, "Open", Dispatch.Method,// new Object[]{word, new Variant(false),new Variant(true)},// new int[1]).toDispatch(); Variant foo = Dispatch.call(docs, "Open", word, false, true); if (foo.getvt() == 0) { return false; } doc = foo.toDispatch();// Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{pdf,new Variant(fmt)}, new int[1]); Dispatch.call(doc, "SaveAs", pdf, fmt); long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start) + "ms."); return true; } catch (Exception ex) { ex.printStackTrace(); System.out.println("转化出错:" + ex.getMessage()); return false; } finally { Dispatch.call(doc, "Close", false); System.out.println("关闭WPS"); if (wps != null) { wps.invoke("Quit", new Variant[]{}); } }} 参考: Java 使用jacob实现doc转pdf(附带其他方法分析) 通过jacob实现office在线预览 Doc 与 Docx 格式互相转换1234567891011121314151617181920212223242526272829303132public static void convertWordFmt(String srcPath, String descPath, int fmt) { long startTime = System.currentTimeMillis(); // 实例化 ComThread 线程与 ActiveXComponent ComThread.InitSTA(); /** * 参数为 Word.Application:需要安装 Office * 参数为 kwps.application:需要安装 WPS * doc 转 docx 时,用 Word.Application 报错 */ ActiveXComponent app = new ActiveXComponent("kwps.Application"); try { // 文档隐藏时进行应用操作 app.setProperty("Visible", new Variant(false)); // 实例化模板 Document 对象 Dispatch document = app.getProperty("Documents").toDispatch(); // 打开 Document 进行另存为操作 Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method, new Object[]{srcPath, new Variant(true), new Variant(true)}, new int[1]).toDispatch(); Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{descPath, new Variant(fmt)}, new int[1]); Dispatch.call(doc, "Close", new Variant(false)); } finally { // 释放线程与 ActiveXComponent app.invoke("Quit", new Variant[]{}); ComThread.Release(); } System.out.println("convert word format successfully, " + "take " + (System.currentTimeMillis() - startTime) / 1000 + " seconds.");} 参考:JAVA实现Doc与Docx互转 分享到: 赞赏 微信扫一扫,向我赞赏 支付宝扫一扫,向我赞赏
如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理