java实现word转pdf(jacob)

word转pdf的方法随便百度一下都是一堆,在此只是想记录一下,方便以后自己查看。

一、在pom文件中引入相应的包:

 <dependency>
    <groupId>net.sf.jacob-project</groupId>
    <artifactId>jacob</artifactId>
    <version>1.14.3</version>
 </dependency>

二、在jdk的jre的bin目录下(C:\Program Files\Java\jdk1.8.0_162\jre\bin)引入jacob-1.14.3-x64.dll文件。

三、代码:

public class WordToPDFUtil {

    private static final int wdFormatPDF = 17;//word保存为pdf的格式宏的值是17

    public static void wToPdfChange(String wordFile, String pdfFile) {//wordFile word 的路径  //pdfFile pdf 的路径

        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            /**
             * app.setProperty("Visible", new Variant(false));
             * 设置word不可见,默认就是不可见的,如果设置可见就是会打开一个word文档
             */
            //app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", wordFile).toDispatch();

            File target = new File(pdfFile);
            // 如果文件存在的话,需要先删除,否则会直接报错
            if (target.exists()) {
                target.delete();
            }
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{
                    pdfFile, new Variant(wdFormatPDF)}, new int[1]);

        } catch (Exception e) {
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            //关闭文档
            Dispatch.call(doc, "Close", false);
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        // 如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }

    public static void main(String[] args) {
        String wordFilePath = "D:\\测试文档.docx";
        String pdfFilePath = "D:\\测试文档.pdf";
        wToPdfChange(wordFilePath, pdfFilePath);
    }
}

原本使用Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);进行保存文档,运行时报错:invoke of: saveas;

后改为Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{ pdfFile, new Variant(wdFormatPDF)}, new int[1]);

(invoke中api最后一个参数是表示错误参数,而不是转换格式的参数)。

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值