whycxzp
2023-06-25 8d110762f4e4aacf02f837aee3598b41a72e1e37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.whyc.util;
 
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
 
public class Word2PdfJacobUtil {
 
    /* 转PDF格式值 */
    private static final int wdFormatPDF = 17;
    /**
     * Word文档转换
     *
     * @param inputFile
     * @param pdfFile
     */
    public static boolean word2PDF(String inputFile, String pdfFile) {
        ComThread.InitMTA(true);
        //long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");// 创建一个word对象
            app.setProperty("Visible", new Variant(false)); // 不可见打开word
            app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性
 
            //System.out.println("打开文档 >>> " + inputFile);
            // Object[]第三个参数是表示“是否只读方式打开”
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
            //System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            // 调用Document对象的SaveAs方法,将文档保存为pdf格式
            // word保存为pdf格式宏,值为17
            Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);// word保存为pdf格式宏,值为17
 
            //long end = System.currentTimeMillis();
 
            //System.out.println("用时:" + (end - start) + "ms.");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("========Error:文档转换失败:" + e.getMessage());
            throw e;
 
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
            // 如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
            ComThread.quitMainSTA();
        }
 
    }
 
    public static void main(String[] arg){
        //String docPath = "C:\\Users\\29550\\Desktop\\研发人员考核方案.docx";
        String docPath = "http://118.89.139.230/zentao/data/upload/1/202205/1721233604702196";
 
        //String pdfPath = "C:\\Users\\29550\\Desktop\\研发人员考核方案2.pdf";
        String pdfPath = "F:\\pdf\\研发人员考核方案2.pdf";
        for (int i = 0; i < 20; i++) {
 
            boolean res = Word2PdfJacobUtil.word2PDF(docPath, pdfPath);
            System.out.println(res);
        }
    }
 
}