使用jacob调用Windows的com对象,转换Office文件为pdf、html等

网友投稿 1160 2022-09-15

使用jacob调用Windows的com对象,转换Office文件为pdf、html等

使用jacob调用Windows的com对象,转换Office文件为pdf、html等

1、介绍

Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。至于什么是COM组件,大家自己Google吧。

2、安装和配置

Jacob是一个开源软件,它的官方站点是:

​​大家可以到上面-源代码研究,也可以直接-编译后的二进制文件。

-包jacob_x.x.zip,解压后有几个文件:jacob.jar、jacob-x.x-M2-x86.dll

把jacob-x.x-M2-x86.dll拷贝到%JAVA_HOME% 下的 bin 目录下,其中,%JAVA_HOME%就是JDK的安装目录。接着直接在java IDE中引用jacob.jar就可以使用了。

下面这个图,本文章中就未列出代码了,在我的资源共享中,有全的源代码,在我之前的博客中也有调用gs转换的命令。

3、转换word为pdf、html、txt 的示例

package com.shanhy.demo.windowsoffice;import java.io.File;import com.jacob.activeX.ActiveXComponent;import com.jacob.com.ComThread;import com.jacob.com.Dispatch;import com.jacob.com.Variant;/** * * 将jacob.dll放入JDK的bin目录下 把jacob.jar放入项目的buildPath中(web项目放到WEB-INF\lib目录下) * * @author 单红宇 * */public class ConvertToPdf { /*转PDF格式值*/ private static final int wdFormatPDF = 17; private static final int xlFormatPDF = 0; private static final int ppFormatPDF = 32; private static final int msoTrue = -1; private static final int msofalse = 0; /*转HTML格式值*/ private static final int wdFormatHTML = 8; private static final int ppFormatHTML = 12; private static final int xlFormatHTML = 44; /*转TXT格式值*/ private static final int wdFormatTXT = 2; public boolean convert2PDF(String inputFile, String pdfFile) { String suffix = getFileSufix(inputFile); File file = new File(inputFile); if (!file.exists()) { System.out.println("文件不存在!"); return false; } if (suffix.equals("pdf")) { System.out.println("PDF not need to convert!"); return false; } if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) { return word2PDF(inputFile, pdfFile); } else if (suffix.equals("ppt") || suffix.equals("pptx")) { return ppt2PDF(inputFile, pdfFile); } else if (suffix.equals("xls") || suffix.equals("xlsx")) { return excel2PDF(inputFile, pdfFile); } else { System.out.println("文件格式不支持转换!"); return false; } } /** * 获取文件后缀 * * @param fileName * @return * @author SHANHY */ private String getFileSufix(String fileName) { int splitIndex = fileName.lastIndexOf("."); return fileName.substring(splitIndex + 1); } /** * Word文档转换 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean word2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application");// 创建一个word对象 app.setProperty("Visible", new Variant(false)); // 不可见打开word app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏 Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性 System.out.println("打开文档 >>> " + inputFile); // Object[]第三个参数是表示“是否只读方式打开” // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch(); // 调用Document对象的SaveAs方法,将文档保存为pdf格式 System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]"); Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);//word保存为pdf格式宏,值为17// Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF); // word保存为pdf格式宏,值为17 long end = System.currentTimeMillis(); System.out.println("用时:" + (end - start) + "ms."); return true; } 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[] {}); } // 如果没有这句话,winword.exe进程将不会关闭 ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * PPT文档转换 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean ppt2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch ppt = null; try { app = new ActiveXComponent("PowerPoint.Application");// 创建一个PPT对象 // app.setProperty("Visible", new Variant(false)); // 不可见打开(PPT转换不运行隐藏,所以这里要注释掉) // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏 Dispatch ppts = app.getProperty("Presentations").toDispatch();// 获取文挡属性 System.out.println("打开文档 >>> " + inputFile); // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document ppt = Dispatch.call(ppts, "Open", inputFile, true,// ReadOnly true,// Untitled指定文件是否有标题 false// WithWindow指定文件是否可见 ).toDispatch(); System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]"); Dispatch.call(ppt, "SaveAs", pdfFile, ppFormatPDF); long end = System.currentTimeMillis(); System.out.println("用时:" + (end - start) + "ms."); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { Dispatch.call(ppt, "Close"); System.out.println("关闭文档"); if (app != null) app.invoke("Quit", new Variant[] {}); } ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * Excel文档转换 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean excel2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch excel = null; try { app = new ActiveXComponent("Excel.Application");// 创建一个PPT对象 app.setProperty("Visible", new Variant(false)); // 不可见打开 // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏 Dispatch excels = app.getProperty("Workbooks").toDispatch();// 获取文挡属性 System.out.println("打开文档 >>> " + inputFile); // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch(); // 调用Document对象方法,将文档保存为pdf格式 System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]"); // Excel 不能调用SaveAs方法 Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, pdfFile); long end = System.currentTimeMillis(); System.out.println("用时:" + (end - start) + "ms."); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { Dispatch.call(excel, "Close", false); System.out.println("关闭文档"); if (app != null) app.invoke("Quit", new Variant[] {}); } ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * 测试 * * @param args * @author SHANHY */ public static void main(String[] args) { ConvertToPdf d = new ConvertToPdf(); d.convert2PDF("g:\\test.docx", "g:\\test.pdf"); d.convert2PDF("g:\\testppt.pptx", "g:\\testppt.pdf"); d.convert2PDF("g:\\testexcel.xlsx", "g:\\testexcel.pdf"); }}

读、写Word的简单示例

import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Variant; import com.jacob.com.Dispatch; public class Word { String strDir = "c:jacob_1.9"; String strInputDoc = strDir + "file_in.doc"; String strOutputDoc = strDir + "file_out.doc"; String strOldText = "[label:import:1]"; String strNewText = "I am some horribly long sentence, so long that [insert anything]"; boolean isVisible = true; boolean isSaveOnExit = true; public Word() { ActiveXComponent oWord = new ActiveXComponent("Word.Application"); oWord.setProperty("Visible", new Variant(isVisible)); Dispatch oDocuments = oWord.getProperty("Documents").toDispatch(); Dispatch oDocument = Dispatch.call(oDocuments, "Open", strInputDoc). toDispatch(); Dispatch oSelection = oWord.getProperty("Selection").toDispatch(); Dispatch oFind = oWord.call(oSelection, "Find").toDispatch(); Dispatch.put(oFind, "Text", strOldText); Dispatch.call(oFind, "Execute"); Dispatch.put(oSelection, "Text", strNewText); Dispatch.call(oSelection, "MoveDown"); Dispatch.put(oSelection, "Text", "nSo we got the next line including BR.n"); Dispatch oFont = Dispatch.get(oSelection, "Font").toDispatch(); Dispatch.put(oFont, "Bold", "1"); Dispatch.put(oFont, "Italic", "1"); Dispatch.put(oFont, "Underline", "0"); Dispatch oAlign = Dispatch.get(oSelection, "ParagraphFormat"). toDispatch(); Dispatch.put(oAlign, "Alignment", "3"); Dispatch oWordBasic = (Dispatch) Dispatch.call(oWord, "WordBasic"). getDispatch(); Dispatch.call(oWordBasic, "FileSaveAs", strOutputDoc); Dispatch.call(oDocument, "Close", new Variant(isSaveOnExit)); oWord.invoke("Quit", new Variant[0]); } public static void main(String[] args) { Word word = new Word(); } }

4、jacob.jar的结构

jacob包括两个部分:

com.jacob.activeX: ActiveXComponent类

com.jacob.com: 其它类和元素

5、Jacob类

Jacob的结构很简单,包含以下几个类:

ActiveXComponent Class:封装了Dispatch对象,用于创建一个封装了COM组件对象的Java Object

Dispatch Class:用于指向封装后的MS数据结构。常用的方法有call,subcall,get,invoke…后面会介绍使用方法。

Variant Class:用于映射COM的Variant数据类型。提供Java和COM的数据交换。

ComException Class:异常类

6、Jacob方法

用于访问COM/DLL对象的方法,读取、修改COM/DLL对象的属性。

call method:属于Dispatch类。用于访问COM/DLL对象的方法。方法进行了重载,方便不同场合调用。返回一个Variant类型的值。

callSub method:使用方法和call一样,不过它不返回值。

get method:读取COM对象的属性值,返回一个Variant类型值。

put method:设置COM对象的属性值。

invoke method:call的另一种用法,更复杂一些。

invokesub method:subcall的另一种用法

getProperty method:属于ActiveXComponent类,读取属性值,返回一个Variant类型值。

setProperty method:属于ActiveXComponent类,设置属性值。

要注意一点:在使用Jacob时,很重要的一点是,用户必须安装有Office的应用程序。否则也就无法建立Java-COM桥,进而无法解析了。

7、最后列一下ActiveX 控件名称

MS控件名

a1的值

InternetExplorer

InternetExplorer.Application

Excel

Excel.Application

Word

Word.Application

Powerpoint

Powerpoint.Application

vb/java Script

ScriptControl

windows media Player

WMPlayer.OCX

Outlook

Outlook.Application

Visio

Visio.Application

DAO

DAO.PrivateDBEngine.35

MultiFace

MultiFace.Face

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Windows 命令行终端 PowerShell 美化计划
下一篇:C#面向对象之继承(曹海涛)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~