java jacob调用office组件将word转pdf

java | 2020-08-27 09:19:33

无论是word还是html转pdf,都有很多方法,但html只有使用浏览器,word只有使用office,才能保证渲染的正确性,所以之前html就研究了 java直接调用google chrome headless浏览器 实现网页转换导出为pdf ,而word转pdf 就需要使用jacob调用office.关于环境配置参考:office(word/excel) DCOM组件权限配置

1.下载jacob

下载地址:https://sourceforge.net/projects/jacob-project/

下载后解压jacob-1.19.zip

 

2.java项目引用jacob

把jacob.jar和jacob-1.19-x64.dll拷贝到resources/lib目录下

2.1安装jacob-1.19-x64.dll

将jacob-1.19-x64.dll放到Java\jdk1.8.0_181\jre\bin下面

或者也可以使用代码来动态加载dll库

public static void loadDriver() throws Exception {
        String dllName=LibraryLoader.getPreferredDLLName();
        log.warn(dllName);
        InputStream inputStream = ResourceUtils.getURL("classpath:lib/"+ dllName + ".dll").openStream();;
        File temporaryDll = File.createTempFile(dllName, ".dll");
        FileOutputStream outputStream = new FileOutputStream(temporaryDll);
        byte[] array = new byte[8192];
        for (int i = inputStream.read(array); i != -1; i = inputStream
                .read(array)) {
            outputStream.write(array, 0, i);
        }
        outputStream.close();
        temporaryDll.deleteOnExit();
        System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll
                .getPath());
        LibraryLoader.loadJacobLibrary();
    }

2.2引用jacob.jar

    <dependency>
      <groupId>com.jacob</groupId>
      <artifactId>jacob</artifactId>
      <version>1.19</version>
      <scope>system</scope>
      <systemPath>${project.basedir}/src/main/resources/lib/jacob.jar</systemPath>
    </dependency>

3.word转pdf代码

public static void word2pdf(String sourceFile,String targetFile) throws Exception {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            //loadDriver();
            ComThread.startMainSTA();
            ComThread.InitMTA(true);

            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            app.setProperty("DisplayAlerts", new Variant(false));

            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", sourceFile,new Variant(false),new Variant(true)).toDispatch();

            Dispatch.call(doc, "SaveAs", targetFile,WORD2PDF_FORMAT);

        }catch (Exception e){
            throw e;
        }
        finally {
            try {
                if(doc!=null)Dispatch.call(doc, "Close", false);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
            try {
                if (app != null) app.invoke("Quit", new Variant[] {});
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
            try {
                ComThread.Release();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
            try {
                ComThread.quitMainSTA();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }

    }

启动之前关闭所有word进程

public static void killOffice(){
        try {
            String commond="taskkill /f /t /im WINWORD.exe";
            Process process=Runtime.getRuntime().exec(commond);
            process.waitFor(10, TimeUnit.SECONDS);

            InputStream inputStream=process.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(process.getInputStream(),baos);
            log.warn("关闭所有office word进程:"+baos.toString("gbk"));
            baos.close();
            inputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } catch (InterruptedException e) {
            log.error(e.getMessage(),e);
        }
    }

 

4.系统配置

设置系统office交互方式

打开任务管理器,32位系统输入”dcomcnfg”,64位输入 mmc comexp.msc 然后回车 展开:“控制台–>“组件服务”–>”计算机”–>“我的电脑”–>”DCOM配置”,找到一个名字类似为”Microsoft Office 97-2003"的节点右键单击该节点,选属性 ->标识选项卡,改为“交互式用户”,最后点击确定完成。

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号