java把word文档转换PDF格式。使用jacob的jar包(限制服务器类型是windows)

代码转换依赖于WPS,请下载WPS。office也行,不过批量转换时可能偶尔会出错
需要的资源包:
jacob-1.18-x64.dll放到你的jdk的bin路径下

链接:https://pan.baidu.com/s/1D2X2pA7ol4HEoEse72iI8w
提取码:cni3
在这里插入图片描述
例如路径
在这里插入图片描述

这里需要的jar包

<dependency>
		<groupId>com.jacob</groupId>
		<artifactId>activeX</artifactId>
		<version>1.18</version>
		<scope>compile</scope>
</dependency>

代码如下:

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import java.io.File;
public class WordToPdf {
    static final int wdFormatPDF = 17;// PDF 格式

    public static void main(String args[]) {
        String wordFile = "D:/demo.doc";
        String pdfFile = "D:/demo.pdf";
        wordToPdf(wordFile,pdfFile);

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

            // 关闭office
            app.invoke("Quit", 0);
            app.safeRelease();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41033385/article/details/106321353