jacob實現文檔轉換

配置環境

下載jacob【下載鏈接】

解壓jacob,將jacob-1.18-x64.dll放在C:\Windows\System32下面

轉換代碼

package com.lx.convert.service;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;

/**
 * @ProjectName: convert
 * @Package: com.lx.convert.service
 * @ClassName: SingletonConvert
 * @Author: 柳絮飛祭奠
 * @Description: 柳絮飛祭奠
 * @Date: 2019/12/12 21:00
 * @Version: 1.0
 */
public class SingletonConvert {
    private static Logger logger = LoggerFactory.getLogger(SingletonConvert.class);
    private static ActiveXComponent app;
    private static ActiveXComponent PPT;
    private static ActiveXComponent EXECL;

    public static final int EXCEL_HTML = 44;

    /**
     * 單例模式
     * 實例化word
     */
    public static synchronized  ActiveXComponent getWordInstance(){
        if (app == null) {
            app =  new ActiveXComponent("KWPS.Application");
            app.setProperty("Visible", false);
        }
        return app;
    }

    public static synchronized ActiveXComponent getPPtInstance(){
        if (PPT == null) {
            PPT =  new ActiveXComponent("KWPP.Application");
        }
        return PPT;
    }
    public static synchronized ActiveXComponent getexeclInstance(){
        if (EXECL == null) {
            EXECL =  new ActiveXComponent("Excel.Application");
        }
        return EXECL;
    }

    /**
     * 轉換word
     */
    public static void wordConvertSingleton(String docPath, String fileName) {
        try {
            app = getWordInstance();
            Dispatch documents = app.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.call(documents, "Open", docPath).toDispatch();
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
                    new Object[] { fileName, new Variant(8) }, new int[1]);
            Dispatch.call(doc, "Close", new Variant(0));
            //沒有調用Quit命令
            doc = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int word2PDF(String srcFilePath, String pdfFilePath) {
//        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
//            ComThread.InitSTA();
            //打開Word應用程序
//            app = new ActiveXComponent("Word.Application"); //office
//            app = new ActiveXComponent("KWPS.Application");  //wps
            app=getWordInstance();
            //TODO
            logger.debug("開始轉化Word爲PDF...");
            long date = System.currentTimeMillis();
            // 設置Word不可見
            // 獲得Word中所有打開的文檔,返回documents對象
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Object[] obj = new Object[]{
                    srcFilePath,
                    //是否只讀
                    new Variant(true),
                    new Variant(true),
                    new Variant(false),
                    new Variant("pwd")
            };
//            Object[] obj = new Object[]{
//                    srcFilePath,
//                    //是否只讀
//                    new Variant(8)
//            };
            // 調用Documents對象中Open方法打開文檔,並返回打開的文檔對象Document
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
            //兼容性檢查,爲特定值false不正確
            // Dispatch.put(doc, "Compatibility", false);
            Dispatch.put(doc, "RemovePersonalInformation", false);
            // word保存爲pdf格式宏,值爲17
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, FileConstants.WORD_TO_PDF_OPERAND);

            //TODO
            logger.debug("doc: " + doc);
            long date2 = System.currentTimeMillis();
            int time = (int) ((date2 - date) / 1000);
            logger.debug("用時:" + time);
            return time;
        } catch (Exception e) {
            e.printStackTrace();
            // throw e;
            logger.debug("Exception" + e);
            return -1;
        } finally {
            if (doc != null) {
                // 關閉文檔
                Dispatch.call(doc, "Close", false);
                doc=null;

            }
//            if (app != null) {
//                // 關閉Word應用程序
//                app.invoke("Quit", 0);
//            }
//            ComThread.Release();
        }
    }


    public static int ppt2pdf(String srcFilePath, String pdfFilePath) {
//        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
//            ComThread.InitSTA();
            // app = new ActiveXComponent("PowerPoint.Application"); //Office
//            app = new ActiveXComponent("KWPP.Application");  //WPS
            PPT =  getPPtInstance();
            //TODO
            logger.debug("開始轉化PPT爲PDF...");
            long date = System.currentTimeMillis();
            Dispatch ppts = PPT.getProperty("Presentations").toDispatch();
            ppt = Dispatch.call(ppts, "Open", srcFilePath,
                    // ReadOnly
                    true,
                    // Untitled指定文件是否有標題
                    true,
                    // WithWindow指定文件是否可見
                    false
            ).toDispatch();
            // ppSaveAsPDF爲特定值32
            // Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND);
            Object[] obj = new Object[]{
                    pdfFilePath,
                    new Variant(FileConstants.PPT_TO_PDF_OPERAND)
            };
            Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, obj, new int[1]);
            long date2 = System.currentTimeMillis();
            int time = (int) ((date2 - date) / 1000);
            logger.debug("用時:" + time);
            return time;
        } catch (Exception e) {
            e.printStackTrace();
            // throw e;
            logger.debug("Exception" + e);
            return -1;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
                ppt=null;
            }
//            if (app != null) {
//                app.invoke("Quit");
//            }
//            ComThread.Release();
        }
    }
    public int excelToHtml(String xlsfile, String htmlfile) {
        long date = new Date().getTime();
        EXECL = getexeclInstance(); // 啓動Excel
//		ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 啓動Excel
        Dispatch excel=null;
        try {
            EXECL.setProperty("Visible", new Variant(false));
            Dispatch excels = EXECL.getProperty("Workbooks").toDispatch();
            excel = Dispatch.invoke(
                    excels,
                    "Open",
                    Dispatch.Method,
                    new Object[] { xlsfile, new Variant(false),new Variant(true) },
                    new int[1]).toDispatch();
//			Dispatch sheet = Dispatch.invoke(excel, "sheet(0)", arg2, arg3, arg4)
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
                    htmlfile, new Variant(EXCEL_HTML) }, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(excel, "Close", f);
            excel=null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close");
                excel=null;
            }
//			app.invoke("Quit", new Variant[] {});
        }
        long date2 = new Date().getTime();
        int time = (int) ((date2 - date) / 1000);
        System.out.println(time+"s");
        return time;
    }

    public int txtToHtml(String xlsfile, String htmlfile) {
        try {
            InputStreamReader nInputStreamReader = new InputStreamReader(new FileInputStream(new File(xlsfile)), "GBK");

            @SuppressWarnings("resource")
            BufferedReader nBufferedReader = new BufferedReader(nInputStreamReader);

            String nHtmlPath =htmlfile;

            File nFile=new File(nHtmlPath);
            if(nFile.exists()){
                nFile.createNewFile();
            }

            FileOutputStream nFileOutputStream = new FileOutputStream(nFile);
            OutputStreamWriter nOutputStreamWriter = new OutputStreamWriter(nFileOutputStream, "UTF-8");
            BufferedWriter nBufferedWriter = new BufferedWriter(nOutputStreamWriter);
            String lineTxt = null;
            while ((lineTxt = nBufferedReader.readLine()) != null) {
                nBufferedWriter.write(lineTxt + "</br>");
            }

            nBufferedWriter.close();
            nOutputStreamWriter.close();
            nOutputStreamWriter.close();
            nFileOutputStream.close();
//
//			org.jsoup.nodes.Document nJsoupDocument = Jsoup.parse(new File(nHtmlPath), "UTF-8");
//			if(nFile.exists() && nFile.isFile()){
//				nFile.delete();
//			}

        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    public static void main(String[] args) {
        SingletonConvert SingletonConvert=new SingletonConvert();
        for (int i=1;i<=11;i++){
            SingletonConvert.excelToHtml("D:\\iWork\\execl\\"+i+".xlsx","D:\\iWork\\execl\\"+i+".html");
//            SingletonConvert.wordConvertSingleton("D:\\iWork\\file.cache\\"+i+".doc","D:\\iWork\\file.cache\\"+i+".html");

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章