java后台用word转成pdf

java后台用word转成pdf

代码

package com.baosight.mro.common.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

import java.io.File;

public class WordToPdf {

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

        ActiveXComponent app = null;
        System.out.println("转换中...");
        // 开始时间
        // long start = System.currentTimeMillis();
        try {
            // 打开word
            app = new ActiveXComponent("Word.Application");
            // 获得word中所有打开的文档
            Dispatch documents = app.getProperty("Documents").toDispatch();
            System.out.println("打开word文件: " + 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);
            Dispatch.call(document, "SaveAs", pdfFile, 17);
            // 关闭文档
            Dispatch.call(document, "Close", false);
        }catch(Exception e) {
            System.out.println("文件转换失败"+e.getMessage());
        }finally {
            // 关闭office
            app.invoke("Quit", 0);
        }
    }

    public static void main(String[] args) {


        String word = "D:/rich.docx";
        String name = "richGong".concat(".pdf");
        String pdf = "D:\\"+name;
        WordToPdfChange(word, pdf);
    }
}

运行即可

你可能感兴趣的:(工具包,java)