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

简介:

1、介绍


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

2、安装和配置

    Jacob是一个开源软件,它的官方站点是: http://danadler.com/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




















部分内容参考: http://www.cnblogs.com/vulcans/archive/2009/09/08/1562588.html




目录
相关文章
|
Web App开发 Windows
【Windows】 chrome 如何下载网站在线预览PDF文件,保存到本地
【Windows】 chrome 如何下载网站在线预览PDF文件,保存到本地
2805 0
|
安全 搜索推荐 iOS开发
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
826 8
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
|
Java BI API
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
这篇文章介绍了如何在Spring Boot项目中整合iTextPDF库来导出PDF文件,包括写入大文本和HTML代码,并分析了几种常用的Java PDF导出工具。
4650 0
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
|
JSON 数据格式
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
1743 2
|
XML JavaScript 测试技术
Web自动化测试框架(基础篇)--HTML页面元素和DOM对象
本文为Web自动化测试入门指南,介绍了HTML页面元素和DOM对象的基础知识,以及如何使用Python中的Selenium WebDriver进行元素定位、操作和等待机制,旨在帮助初学者理解Web自动化测试中的关键概念和操作技巧。
308 1
|
数据采集 移动开发 前端开发
springboot使用html模版导出pdf文档
springboot使用html模版导出pdf文档
|
JavaScript 前端开发 容器
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
2862 0
|
移动开发 前端开发 JavaScript
使用html-to-image代替html2canvas,结合jspdf实现下载pdf(下载截图下载前端dom元素)
本文介绍了在前端项目中,当使用`html2canvas`遇到问题时,如何使用`html-to-image`库作为替代方案,结合`jspdf`实现将DOM元素生成为PDF文件并提供下载。文章首先讨论了`html2canvas`可能遇到的问题,并提供了该库的使用示例代码。随后,详细介绍了`html-to-image`库的安装和使用方法,展示了如何将DOM元素转换为Canvas,再利用`jspdf`生成PDF文件。最后,文章通过示例代码说明了整个转换和下载的过程,并展示了效果截图。
1787 0
使用LabVIEW打开默认应用程序中的文档(PDF,Word,Excel,Html)
使用LabVIEW的"Open a Document on Disk.vi",存于<LabVIEW>\vi.lib\Platform\browser.llb,可让默认应用打开硬盘文档。此VI仅基础打开功能,高级控制推荐LabVIEW Report Generation Toolkit或ActiveX。注意:避免版本升级问题,最好将VI复制到vi.lib外的目录。
788 3
|
Unix Linux Shell
Sphinx是一个Python文档生成工具,它可以解析reStructuredText或Markdown格式的源代码注释,并生成多种输出格式,如HTML、LaTeX、PDF、ePub等。
Sphinx是一个Python文档生成工具,它可以解析reStructuredText或Markdown格式的源代码注释,并生成多种输出格式,如HTML、LaTeX、PDF、ePub等。