WordToPdf.java 7.93 KB
Newer Older
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
package leaf.plugin.word2pdf;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uncertain.core.UncertainEngine;
import uncertain.ocm.IObjectRegistry;

import java.io.File;

/**
 * @author niminmin
 */
public class WordToPdf {
    IObjectRegistry registry;
    String jacobDllPath;
    private static final Logger logger = LoggerFactory.getLogger(WordToPdf.class);
    public WordToPdf(IObjectRegistry registry, String jacobDllName)
            throws Exception {
        this.registry = registry;
        UncertainEngine engine = (UncertainEngine) this.registry
                .getInstanceOfType(UncertainEngine.class);
        String webInfPath = engine.getDirectoryConfig().getConfigDirectory();

        // 添加jacob-1.18-x64.dll到C:\Java\jre1.7.0_79\bin目录 或者按照以下代码进行设置
        // D:\work\leafProjects\MX_leasing\web\WEB-INF\server-script\jacob\jacob-1.18-x64.dll
gzj34291's avatar
gzj34291 committed
31
        jacobDllPath = webInfPath + "/server-script/jacob/" + jacobDllName;
32 33
        System.setProperty("jacob.dll.path", jacobDllPath);
        System.setProperty("com.jacob.debug", "true");
34
        logger.info("加载的配置文件路径:" + jacobDllPath);
35 36 37 38
    }

    public static boolean word2pdf(String inFilePath, String outFilePath) {
        logger.info("Word转PDF开始启动...");
39
        logger.info("Word转PDF开始启动..."+outFilePath);
40 41 42 43 44
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        boolean flag = false;
        try {
45
            ComThread.InitMTA();
46
            app = new ActiveXComponent("Word.Application");
gzj34291's avatar
gzj34291 committed
47
            //  logger.info("Word转PDF开始启动...234");
48
            app.setProperty("Visible", new Variant(false));
gzj34291's avatar
gzj34291 committed
49
            //  logger.info("Word转PDF开始启动...456");
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
            Dispatch docs = app.getProperty("Documents").toDispatch();
            logger.info("打开文档:" + inFilePath);
            doc = Dispatch.invoke(
                    docs,
                    "Open",
                    1,
                    new Object[]{inFilePath, new Variant(false),
                            new Variant(true)}, new int[1]).toDispatch();
            logger.info("转换文档到PDF:" + outFilePath);
            File tofile = new File(outFilePath);
            if (tofile.exists()) {
                tofile.delete();
            }

            Dispatch.invoke(doc, "SaveAs", 1, new Object[]{outFilePath,
                    new Variant(17)}, new int[1]);
            Dispatch.call(doc, "Close", new Object[]{new Variant(false)});
            long end = System.currentTimeMillis();
            logger.info("转换完成,用时:" + (end - start) + "ms");
            flag = true;
        } catch (Exception e) {
gzj34291's avatar
gzj34291 committed
71
            // logger.error("error",e);
72
            logger.info("Word转PDF出错:" + e.getMessage());
gzj34291's avatar
gzj34291 committed
73
            //  logger.info("Word转PDF出错:" + e.toString());
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
            flag = false;
            logger.info("关闭文档");
            if (app != null) {
                app.invoke("Quit", 0);
            }

            ComThread.Release();
        } finally {
            logger.info("关闭文档");
            if (app != null) {
                app.invoke("Quit", 0);
            }

            ComThread.Release();
        }
        return flag;
    }

    /**
     * 如果PDF存在则删除PDF
     *
     * @param pdfPath
     */
    private static void deletePdf(String pdfPath) {
        File pdfFile = new File(pdfPath);
        if (pdfFile.exists()) {
            pdfFile.delete();
        }
    }


    /**
     * excel to pdf
     *
     * @param inFilePath
     * @param outFilePath
110 111
     * @param fitToPagesTall  所有行为一页
     * @param fitToPagesWide  所有列为一页
112 113
     * @return
     */
114
    public static boolean excel2pdf(String inFilePath, String outFilePath,Object fitToPagesTall,Object fitToPagesWide) {
115 116 117 118 119 120 121
        ActiveXComponent activeXComponent = new ActiveXComponent("Excel.Application");
        activeXComponent.setProperty("Visible", false);

//		deletePdf(outFilePath);

        Dispatch excels = activeXComponent.getProperty("Workbooks").toDispatch();
        Dispatch excel = Dispatch.call(excels, "Open", inFilePath, false, true).toDispatch();
122 123 124 125 126 127 128
        Dispatch currentSheet = Dispatch.get((Dispatch) excel,
                "ActiveSheet").toDispatch();
        Dispatch pageSetup = Dispatch.get(currentSheet, "PageSetup")
                .toDispatch();
        //Dispatch.put(pageSetup, "Zoom", 50);
        Dispatch.put(pageSetup, "FitToPagesTall", fitToPagesTall);
        Dispatch.put(pageSetup, "FitToPagesWide", fitToPagesWide);
129 130 131 132 133
        Dispatch.call(excel, "ExportAsFixedFormat", 0, outFilePath);
        Dispatch.call(excel, "Close", false);
        activeXComponent.invoke("Quit");
        return true;
    }
gzj34291's avatar
gzj34291 committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    public static boolean exceltopdf(String inFilePath, String outFilePath) {
        ActiveXComponent activeXComponent = new ActiveXComponent("Excel.Application");
        activeXComponent.setProperty("Visible", false);

//		deletePdf(outFilePath);

        Dispatch excels = activeXComponent.getProperty("Workbooks").toDispatch();
        Dispatch excel = Dispatch.call(excels, "Open", inFilePath, false, true).toDispatch();
        Dispatch currentSheet = Dispatch.get((Dispatch) excel,
                "ActiveSheet").toDispatch();
        Dispatch pageSetup = Dispatch.get(currentSheet, "PageSetup")
                .toDispatch();
        //Dispatch.put(pageSetup, "Zoom", 50);
        Dispatch.put(pageSetup, "FitToPagesTall", 1);
        Dispatch.put(pageSetup, "FitToPagesWide", 1);
        Dispatch.call(excel, "ExportAsFixedFormat", 0, outFilePath);
        Dispatch.call(excel, "Close", false);
        activeXComponent.invoke("Quit");
        return true;
    }
154 155 156 157 158 159 160 161 162 163 164 165

    /**
     * excel to pdf Orientation  excel横向转成pdf
     *
     * @param inFilePath
     * @param outFilePath
     * @return
     */
    public static boolean excel2pdfOrientation(String inFilePath, String outFilePath) {
        ActiveXComponent activeXComponent = new ActiveXComponent("Excel.Application");
        activeXComponent.setProperty("Visible", false);

gzj34291's avatar
gzj34291 committed
166
        //deletePdf(outFilePath);
167 168 169 170 171 172 173 174 175

        Dispatch excels = activeXComponent.getProperty("Workbooks").toDispatch();
        Dispatch excel = Dispatch.call(excels, "Open", inFilePath, false, true).toDispatch();

        Dispatch currentSheet = Dispatch.get((Dispatch) excel,
                "ActiveSheet").toDispatch();
        Dispatch pageSetup = Dispatch.get(currentSheet, "PageSetup")
                .toDispatch();
        Dispatch.put(pageSetup, "Orientation", new Variant(2));
176
        //设置缩放,值为100或false
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

        Dispatch.call(excel, "ExportAsFixedFormat", 0, outFilePath);
        Dispatch.call(excel, "Close", false);
        activeXComponent.invoke("Quit");
        return true;
    }
    public static void cutPdf(String pdfPath)
    {
        File file = new File(pdfPath);
        PDDocument document = new PDDocument();
        try{
            document = PDDocument.load(file);
        }catch(Exception e){
            logger.error("error",e);
        }
        int noOfPages = document.getNumberOfPages();
        System.out.println(noOfPages);
        document.removePage(noOfPages-1);

        try{
            document.save(pdfPath);
            document.close();
        }catch(Exception e){
            logger.error("error",e);
        }
    }



    public static void main(String[] args) throws Exception {
207

gzj34291's avatar
gzj34291 committed
208 209 210 211 212 213
        String jacobDllPath = "D:\\workspace\\leaf-hlcm\\src\\main\\webapp\\WEB-INF\\server-script\\jacob\\jacob-1.19-x64.dll";
        System.setProperty("jacob.dll.path", jacobDllPath);
        System.setProperty("com.jacob.debug", "true");

        //exceltopdf("D:\\u01\\hls_file\\excel\\2023\\03\\对账单(张武林_LZJ20010006)202303131039.xlsx", "D:\\u01\\hls_file\\excel\\2023\\01\\f.pdf");
    }
214
}