Jacob 文件转PDF

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jeesite.modules.common.entity.AttachmentConfig;
import java.io.*;


/**
 * 张文科
 * 转PDF工具
 */
public class JacobToPDF {
    /*转PDF格式值*/
    private static final int wdFormatPDF = 17;
    private static final int xlFormatPDF = 0;
    private static final int ppFormatPDF = 32;
    private static final int msoTrue = -1;
    private static final int msofalse = 0;
    /*转HTML格式值*/
    private static final int wdFormatHTML = 8;
    private static final int ppFormatHTML = 12;
    private static final int xlFormatHTML = 44;
    /*应用*/
    private static final String WORK = "Word.Application";
    private static final String EXCEL = "Excel.Application";
    private static final String PPT = "PowerPoint.Application";
    /*
    jacob配置
       把jacob[version].dll放入 jdk[version]\jre\bin目录下.
       把jacob[version].jar放入 jdk[version]\jre\lib\ext目录下.
       选择性追加:把jacob[version].dll放入 Window\system32\目录下
       如果还是报错,查看自己项目的使用的jdk目录,同上
       为了方便管理可以将其jar包安装到maven
          mvn install:install-file
          -Dfile=C:\...\jacob-1.20\jacob.jar #配置jar包所在目录
          -DgroupId=com.jacob #配置生成jar包的groupId
          -DartifactId=jacob #配置生成jar包的artifactId
          -Dpackaging=jar #配置文件的打包方式
          -Dversion=1.20 #配置版本号,只需符合Maven版本号规则即可
       然后就可以引入依赖:
          <dependency>
            <groupId>com.jacob</groupId>
            <artifactId>jacob</artifactId>
            <version>1.20</version>
          </dependency>
       注:dll文件还是一样同之前一样配置的
       git下载地址:https://github.com/freemansoft/jacob-project/releases
       并且需要运行环境安装office以及插件SaveAsPDFandXPS.exe
       缺点:window环境,并且比较慢
       优点:原生,兼容性好,格式准确
    */

    /**
     * 转PDF
     * 支持的文件类型doc、docx、txt、ppt、pptx,xls、xlsx
     * @param inputFile 源文件
     * @return
     */
    public static File convertPDF(String inputFile) {
        String suffix = ZipUtil.getFileSuffix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            System.out.println("文件不存在!");
            return null;
        }
        if (suffix.equals("pdf")) {
            System.out.println("pdf文件无需转换!");
            return file;
        }
        String name = file.getName().substring(0,file.getName().lastIndexOf("."));
        String mkdirs = ZipUtil.getMkdirs(inputFile)+ AttachmentConfig.config.getConvertPath();
        ZipUtil.createMkdirs(mkdirs);
        String outPath=mkdirs+File.separator+name+".pdf";
        File pdfFile = new File(outPath);
        if(pdfFile.exists()) pdfFile.delete();
        
        if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            return wordPDF(inputFile, outPath);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            return pptPDF(inputFile, outPath);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            return excelPDF(inputFile, outPath);
        } else {
            System.out.println("文件格式不支持转换!");
            return null;
        }
    }

    /**
     * word文件转PDF
     * @param inputFile 输入文件
     * @param pdfFile 输出文件
     * @return
     */
    public static File wordPDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        File file = null;
        try {
//            ComThread.InitSTA();//仅允许一个线程池中一个线程运行,其他线程上锁
            ComThread.InitMTA(true);//允许同时有多个WORD进程运行
            //创建office上的一个应用,比如work、excel等
            app = new ActiveXComponent(WORK);
            //设置word以不可见打开
            app.setProperty("Visible", false);
            //获得word中所有打开的文档,返回Documents对象Dispatch
            Dispatch docs = app.getProperty("Documents").toDispatch();
            //打开文档,并返回打开的文档的Document对象
            doc = Dispatch.call(
                    docs,
                    "Open",//操作指令
                    inputFile,//文件地址
                    false,//是否只读
                    true//是否显示标题
            ).toDispatch();
            //另存为
            Dispatch.call(
                    doc,
                    "SaveAs",//另存指令还有“SaveAs”
                    pdfFile,
                    wdFormatPDF//word保存为pdf格式宏,值为17
            );
            file = new File(pdfFile);
        } catch (Exception e) {
            throw new RuntimeException("work文件另存异常",e);
        } finally {
            //关闭文档
            if (doc != null) {
                Dispatch.call(doc, "Close");
            }
            //关闭office
            if (app != null) {
                app.invoke("Quit",new Variant[]{});
            }
            //释放线程
            ComThread.Release();
        }
        return file;
    }

    /**
     * excel文件转PDF
     * @param inputFile 输入文件
     * @param pdfFile 输出文件
     * @return
     */
    private static File excelPDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch excel = null;
        File file = null;
        boolean result = true;
        try {
            ComThread.InitMTA(true);
            app = new ActiveXComponent(EXCEL);
//            app.setProperty("Visible", false);
            Dispatch.put(app,"Visible",false);
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            excel = Dispatch.call(
                    excels,
                    "Open",
                    inputFile,
                    false,
                    true
            ).toDispatch();
            /***解决表格列太多,造成分页显示***/
            //获取到sheets的集合对象
            Dispatch sheets = Dispatch.get(excel, "sheets").toDispatch();
            //获取到总表数
            int count = Dispatch.get(sheets, "count").changeType(Variant.VariantInt).getInt();
            for (int i = 1; i <= count; i++) {
                //获取到sheet页
                Dispatch sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[]{i}, new int[1]).toDispatch();
                Dispatch page = Dispatch.get(sheet, "PageSetup").toDispatch();
                //是否设置区域打印
                Dispatch.put(page, "PrintArea", false);
                //设置横向打印还是纵向打印
                Dispatch.put(page, "Orientation", 2);
                //设置缩放,值为100或false
                Dispatch.put(page, "Zoom", false);
                //所有行为一页
                Dispatch.put(page, "FitToPagesTall", false);
                //所有列为一页
                Dispatch.put(page, "FitToPagesWide", false);
            }
            Dispatch.call(
                    excel,
                    "ExportAsFixedFormat",
                    xlFormatPDF,
                    pdfFile
            );
            file = new File(pdfFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Excel文件另存异常", e);
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close",false);
            }
            if (app != null) {
                app.invoke("Quit",new Variant[]{});
            }
            ComThread.Release();
        }
        return file;
    }

    /**
     * ppt文件转PDF
     * @param inputFile 输入文件
     * @param pdfFile 输出文件
     * @return
     */
    private static File pptPDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        File file = null;
        try {
            ComThread.InitMTA(true);
            app = new ActiveXComponent(PPT);
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            ppt = Dispatch.call(
                    ppts,
                    "Open",
                    inputFile,
                    true,
                    true,
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            Dispatch.call(
                    ppt,
                    "SaveAs",
                    pdfFile,
                    ppFormatPDF
            );
            file = new File(pdfFile);
        } catch (Exception e) {
            throw new RuntimeException("ppt文件另存异常",e);
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit",new Variant[]{});
            }
            ComThread.Release();
        }
        return file;
    }

    /**
     * excel转Html
     */
    private static boolean excelToHtml(String xlsfile, String htmlfile) {
        ActiveXComponent app = null;
        Dispatch excel = null;
        boolean result = true;
        try {
            ComThread.InitMTA(true);
            app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", false);
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            excel = Dispatch.call(
                    excels,
                    "Open",
                    xlsfile,
                    false,
                    true
            ).toDispatch();
            Dispatch.call(
                    excel,
                    "SaveAs",
                    htmlfile,
                    xlFormatHTML);
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        } finally{
            if (excel != null) {
                Dispatch.call(excel, "Close");
            }
            if (app != null) {
                app.invoke("Quit",new Variant[]{});
            }
            ComThread.Release();
        }
        return result;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容