word转pdf、excel转pdf、ppt转pdf

1、调用实例

//我这个是将word转成pdf并下载的,你自己的啥样,根据实际情况做
public void packdownload(HttpServletResponse response) throws IOException {
    File aaaPdf = wordToPdf(new File("E:\\", "aaa.word"), new File("E:\\", "aaa.pdf"));
    
    //拼接下载默认名称并转为ISO-8859-1格式
    String fileName = new String(("aaa.pdf").getBytes(),"ISO-8859-1");
    response.setHeader("Content-Disposition", "attchment;filename="+fileName);
    //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
    ServletOutputStream outputStream = response.getOutputStream();
    FileInputStream inputStream = new FileInputStream(aaaPdf);
    // 如果是SpringBoot框架,在这个路径
    // org.apache.tomcat.util.http.fileupload.IOUtils产品
    // 否则需要自主引入apache的 commons-io依赖
    // copy方法为文件复制,在这里直接实现了下载效果
    IOUtils.copy(inputStream, outputStream);
    // 关闭输入流
    inputStream.close();
    //下载完成之后,删掉这个文件
    aaaPdf.delete();
}

/**
 * word 转 pdf
 *
 * @param wordFile
 * @param pdfFile
 * @return
 */
 private File wordToPdf(File wordFile, File pdfFile) {
    ConvertToPdf d = new ConvertToPdf();
    d.convert2PDF(wordFile.getPath(), pdfFile.getPath());
    return pdfFile;
 }

2、工具类

package io.zcy.common.utils;//包名改成自己的,别报个错就怪别人,你自己的包名,别人怎么知道

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

import java.io.File;

/**
 * 将jacob.dll放入JDK的bin目录下 把jacob.jar放入项目的buildPath中(web项目放到WEB-INF\lib目录下)
 *
 * @author zcy
 * @create 2021/03/23
 */
public class ConvertToPdf {

    /*转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;
    /*转TXT格式值*/
    private static final int wdFormatTXT = 2;

    /**
     * inputFile为输入的word,excel,ppt文件的全路径
     * pdfFile为输出路径,也是需要把文件创建好的,你别傻乎乎的去文件夹里创建就好了
     */

    public boolean convert2PDF(String inputFile, String pdfFile) {
        String suffix = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            System.out.println("文件不存在!");
            return false;
        }
        if (suffix.equals("pdf")) {
            System.out.println("PDF not need to convert!");
            return false;
        }
        if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            return word2PDF(inputFile, pdfFile);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            return ppt2PDF(inputFile, pdfFile);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            return excel2PDF(inputFile, pdfFile);
        } else {
            System.out.println("文件格式不支持转换!");
            return false;
        }
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     * @author SHANHY
     */
    private String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }

    /**
     * Word文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    private boolean word2PDF(String inputFile, String pdfFile) {
        ComThread.InitSTA();

        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();
            // 调用Document对象的SaveAs方法,将文档保存为pdf格式
            System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);//word保存为pdf格式宏,值为17
//         Dispatch.call(doc, "ExportAsFixedFormat", 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());
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        // 如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
        ComThread.quitMainSTA();
        return false;
    }

    /**
     * PPT文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    private boolean ppt2PDF(String inputFile, String pdfFile) {
        ComThread.InitSTA();

        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            app = new ActiveXComponent("PowerPoint.Application");// 创建一个PPT对象
            // app.setProperty("Visible", new Variant(false)); // 不可见打开(PPT转换不运行隐藏,所以这里要注释掉)
            // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch ppts = app.getProperty("Presentations").toDispatch();// 获取文挡属性

            System.out.println("打开文档 >>> " + inputFile);
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            ppt = Dispatch.call(ppts, "Open", inputFile,
                    true,// ReadOnly
                    true,// Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();

            System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            Dispatch.call(ppt, "SaveAs", pdfFile, ppFormatPDF);

            long end = System.currentTimeMillis();

            System.out.println("用时:" + (end - start) + "ms.");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(ppt, "Close");
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        ComThread.Release();
        ComThread.quitMainSTA();
        return false;
    }

    /**
     * Excel文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    private boolean excel2PDF(String inputFile, String pdfFile) {
        ComThread.InitSTA();

        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch excel = null;
        try {
            app = new ActiveXComponent("Excel.Application");// 创建一个PPT对象
            app.setProperty("Visible", new Variant(false)); // 不可见打开
            // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = app.getProperty("Workbooks").toDispatch();// 获取文挡属性

            System.out.println("打开文档 >>> " + inputFile);
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
            // 调用Document对象方法,将文档保存为pdf格式
            System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            // Excel 不能调用SaveAs方法
            Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, pdfFile);

            long end = System.currentTimeMillis();

            System.out.println("用时:" + (end - start) + "ms.");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(excel, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        ComThread.Release();
        ComThread.quitMainSTA();
        return false;
    }

    /**
     * 测试
     * 测试的时候记得把文件创建出来,别死脑经说不管用
     * @param args
     * @author SHANHY
     */
    public static void main(String[] args) {
        ConvertToPdf d = new ConvertToPdf();
        d.convert2PDF("g:\\test.docx", "g:\\test.pdf");
        d.convert2PDF("g:\\testppt.pptx", "g:\\testppt.pdf");
        d.convert2PDF("g:\\testexcel.xlsx", "g:\\testexcel.pdf");
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阁下大名

您的鼓励就是我前进的动力,谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值