关于jacob的总结

1.jacob 需要服务器上面有  office组件

2. dll文件不需要注册,直接放在jdk/bin目录下即可。

wordtopdf


/**
 *
 * @param wordInputFilePath 必须是存在的路径文件才可以转换
 * @param pdfOutFilePath    输出的位置
 */

public static void Word2Pdf(String wordInputFilePath,String pdfOutFilePath){
    ActiveXComponent app = null;

    try {
        // 打开word
        System.out.println(System.getProperty("java.library.path"));
        app = new ActiveXComponent("Word.Application");
        // 设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的
        //app.setProperty("Visible", false);
        // 获得word中所有打开的文档
        Dispatch documents = app.getProperty("Documents").toDispatch();
        System.out.println("打开文件: " + wordInputFilePath);
        // 打开文档
        Dispatch document = Dispatch.call(documents, "Open", wordInputFilePath, false, true).toDispatch();
        // 如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在
        File target = new File(pdfOutFilePath);
        if (target.exists()) {
            target.delete();
        }
        System.out.println("另存为: " + pdfOutFilePath);
        // 另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17
        Dispatch.call(document, "SaveAs", pdfOutFilePath, 17);
        // 关闭文档
        Dispatch.call(document, "Close", false);
        // 结束时间
        long end = System.currentTimeMillis();
    }catch(Exception e) {
        e.getMessage();
        System.out.println("转换失败"+e.getMessage());
    }finally {
        // 关闭office
        app.invoke("Quit", 0);
    }
}

一直不知道什么问题,原来是服务器没有office组件,太坑了。

发布了45 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zyc050707/article/details/104049632