使用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




目录
相关文章
|
16天前
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
3月前
|
人工智能 编解码 文字识别
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
OCRmyPDF 是一款开源命令行工具,专为将扫描的 PDF 文件转换为可搜索、可复制的文档。支持多语言、图像优化和多核处理。
511 17
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
|
3月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
266 5
|
3月前
|
文字识别 BI
【图片型PDF】批量识别扫描件PDF指定区域局部位置内容,将识别内容导出Excel表格或批量改名文件,基于阿里云OCR对图片型PDF识别改名案例实现
在医疗和政务等领域,图片型PDF文件(如病历、报告、公文扫描件)的处理需求广泛。通过OCR技术识别这些文件中的文字信息,提取关键内容并保存为表格,极大提高了信息管理和利用效率。本文介绍一款工具——咕嘎批量OCR系统,帮助用户快速处理图片型PDF文件,支持区域识别、内容提取、导出表格及批量改名等功能。下载工具后,按步骤选择处理模式、进行区域采样、批量处理文件,几分钟内即可高效完成数百个文件的处理。
323 8
|
4月前
|
机器学习/深度学习 人工智能 文字识别
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
Zerox 是一款开源的本地化高精度OCR工具,基于GPT-4o-mini模型,支持PDF、DOCX、图片等多种格式文件,能够零样本识别复杂布局文档,输出Markdown格式结果。
356 4
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
|
5月前
|
人工智能 文字识别 数据挖掘
MarkItDown:微软开源的多格式转Markdown工具,支持将PDF、Word、图像和音频等文件转换为Markdown格式
MarkItDown 是微软开源的多功能文档转换工具,支持将 PDF、PPT、Word、Excel、图像、音频等多种格式的文件转换为 Markdown 格式,具备 OCR 文字识别、语音转文字和元数据提取等功能。
805 9
MarkItDown:微软开源的多格式转Markdown工具,支持将PDF、Word、图像和音频等文件转换为Markdown格式
|
5月前
|
JavaScript
jquery图片和pdf文件预览插件
EZView.js是一款jquery图片和pdf文件预览插件。EZView.js可以为图片和pdf格式文件生成在线预览效果。支持的文件格式有pdf、jpg、 png、jpeg、gif。
140 16
|
7月前
|
Java Apache Maven
将word文档转换成pdf文件方法
在Java中,将Word文档转换为PDF文件可采用多种方法:1) 使用Apache POI和iText库,适合处理基本转换需求;2) Aspose.Words for Java,提供更高级的功能和性能;3) 利用LibreOffice命令行工具,适用于需要开源解决方案的场景。每种方法都有其适用范围,可根据具体需求选择。
|
7月前
|
Java Apache Maven
Java将word文档转换成pdf文件的方法?
【10月更文挑战第13天】Java将word文档转换成pdf文件的方法?
2163 1
|
7月前
|
JavaScript 前端开发 容器
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
751 0

热门文章

最新文章