package com.ruoyi.common.utils.file;

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

import java.io.File;

/** 使用COM组件将文档转换为PDF版式文件 */
public class WordToPdf {

    private static final Integer WORD_TO_PDF_OPERAND = 17;
    private static final Integer PPT_TO_PDF_OPERAND = 32;
    private static final Integer EXCEL_TO_PDF_OPERAND = 0;

    public static void doc2pdf(String srcFilePath) throws Exception {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Object[] obj = new Object[] {srcFilePath, new Variant(false), new Variant(true)};
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
            //          Dispatch.put(doc, "Compatibility", false);  //兼容性检查,为特定值false不正确
            Dispatch.put(doc, "RemovePersonalInformation", false);
            File srcFile = new File(srcFilePath);
            String fileName = srcFile.getName();
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            String pdfFilePath = srcFile.getParent().replaceAll("word","pdf") + "/" + fileName + ".pdf";
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏，值为17

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }

    //测试用例
  /*  public static void main(String args[]) throws Exception {
        WordToPdf.doc2pdf("E:/裕华区福大神农产品经销中心/3.住所（经营场所）信息申报表.doc");

    }*/
}
