Java使用jacob实现各类办公文档(ppt,Excel,word,text,imge)转换成PDF

本文介绍了一个实用工具,能够将多种类型的文件(如DOC、XLS、PPT等)转换为PDF格式。通过利用Java和COM组件,该工具支持常见的办公文档格式,并提供了详细的实现步骤和技术细节。

//代码中都有注释,使用注解的地方大家可以略过

package com.frank.demo.file.common.util;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import com.mongodb.gridfs.GridFSDBFile;


@Component
public class FlieToPdfUtil {


    @Autowired
    private GridFsTemplate fileRepository;


    private static final int wdFormatPDF = 17;
    private static final int xlTypePDF = 0;
    private static final int ppSaveAsPDF = 32;


    // 记录日志信息
    private static Logger logger = LoggerFactory.getLogger(FlieToPdfUtil.class);


    public ByteArrayOutputStream fileToPdf(String fileId) throws Exception {
        GridFSDBFile gridFSDBFile = fileRepository.findOne(new Query(Criteria.where("_id").is(fileId)));
        if (null != gridFSDBFile) {
            String type = this.getFileSufix(gridFSDBFile.getFilename());
            String folder = System.getProperty("java.io.tmpdir");
            if (type.equalsIgnoreCase("doc") || type.equalsIgnoreCase("docx") || type.equalsIgnoreCase("txt") || type.equalsIgnoreCase("wps")) {
                StringBuffer filePath = new StringBuffer();
                String name = this.generateToken();
                filePath.append(folder);
                filePath.append(name);
                filePath.append("." + type);
                this.readFile(gridFSDBFile, filePath.toString());
                StringBuffer pdfPath = new StringBuffer();
                pdfPath.append(folder);
                pdfPath.append(name);
                pdfPath.append(".pdf");
                this.wordToPDF(filePath.toString(), pdfPath.toString());
                this.deleteFile(filePath.toString());
                return this.getBytes(pdfPath.toString());
            } else if (type.equalsIgnoreCase("ppt") || type.equalsIgnoreCase("pptx")) {
                StringBuffer filePath = new StringBuffer();
                String name = this.generateToken();
                filePath.append(folder);
                filePath.append(name);
                filePath.append("." + type);
                this.readFile(gridFSDBFile, filePath.toString());
                StringBuffer pdfPath = new StringBuffer();
                pdfPath.append(folder);
                pdfPath.append(name);
                pdfPath.append(".pdf");
                this.pptToPDF(filePath.toString(), pdfPath.toString());
                this.deleteFile(filePath.toString());
                return this.getBytes(pdfPath.toString());
            } else if (type.equalsIgnoreCase("xls") || type.equalsIgnoreCase("xlsx")) {
                StringBuffer filePath = new StringBuffer();
                String name = this.generateToken();
                filePath.append(folder);
                filePath.append(name);
                filePath.append("." + type);
                this.readFile(gridFSDBFile, filePath.toString());
                StringBuffer pdfPath = new StringBuffer();
                pdfPath.append(folder);
                pdfPath.append(name);
                pdfPath.append(".pdf");
                this.excelToPDF(filePath.toString(), pdfPath.toString());
                this.deleteFile(filePath.toString());
                return this.getBytes(pdfPath.toString());
            } else if (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("gif")) {
                StringBuffer filePath = new StringBuffer();
                String name = this.generateToken();
                filePath.append(folder);
                filePath.append(name);
                filePath.append("." + type);
                this.readFile(gridFSDBFile, filePath.toString());
                StringBuffer pdfPath = new StringBuffer();
                pdfPath.append(folder);
                pdfPath.append(name);
                pdfPath.append(".pdf");
                this.imgToPDF(filePath.toString(), pdfPath.toString());
                this.deleteFile(filePath.toString());
                return this.getBytes(pdfPath.toString());
            } else {
                InputStream is = gridFSDBFile.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) > -1) {
                    baos.write(buffer, 0, len);
                }
                is.close();
                baos.flush();
                return baos;
            }
        } else {
            throw new Exception("文件不存在!");
        }
    }


    /**
     * 删除单个文件
     *  
     *
     * @param sPath             被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    /**
     * 写入当前文件
     */
    public void readFile(GridFSDBFile gridFSDBFile, String filePath) throws Exception {
        InputStream is = gridFSDBFile.getInputStream();
        FileOutputStream os = new FileOutputStream(filePath);
        int index = 0;
        while ((index = is.read()) != -1) {
            os.write(index);
        }
        is.close();
        os.close();
    }


    /**
     * 获取pdf文件输出流
     */
    public ByteArrayOutputStream getBytes(String filePath) {
        File file = new File(filePath);
        ByteArrayOutputStream out = null;
        try {
            FileInputStream in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            while ((in.read(b)) != -1) {
                out.write(b, 0, b.length);
            }
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.deleteFile(filePath.toString());
        return out;
    }


    /**
     * 获取随机名称
     */
    public String generateToken() throws Exception {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /***
     * 判断文件类型
     * 
     * @param fileName
     * @return
     */
    public String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }


    /**
     * Word转PDF
     */
    private void wordToPDF(String inputFile, String pdfFile) {
        logger.info("启动 Word...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = new Dispatch();
        try {
            logger.info("进入转换PDF程序");
            app = new ActiveXComponent("Word.Application");
            Dispatch xlo = (Dispatch) (app.getObject());
            try {
                logger.info("version=" + app.getProperty("Version"));
                logger.info("version=" + Dispatch.get(xlo, "Version"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", inputFile).toDispatch();
            logger.info("打开文档..." + inputFile);
            logger.info("转换文档到 PDF..." + pdfFile);
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", pdfFile, // FileName
                    wdFormatPDF);
            long end = System.currentTimeMillis();
            logger.info("转换完成..用时:" + (end - start) + "ms.");


        } catch (Exception e) {
            logger.info("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
            // 如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
        }


    }


    /**
     * Excel转化成PDF
     */
    private void excelToPDF(String inputFile, String pdfFile) {
        ActiveXComponent ax = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA(true);
            logger.info("进入转换PDF程序");
            ax = new ActiveXComponent("KET.Application");
            logger.info("开始转换Excel为PDF...");
            long start = System.currentTimeMillis();
            ax.setProperty("Visible", false);
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();
            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[]{inputFile, new Variant(false), new Variant(false)}, new int[9]).toDispatch();
            Dispatch sheet;
            // 横向打印设置 多个Sheet
            Dispatch sheets = Dispatch.get(excel, "Sheets").toDispatch();
            // 获得几个sheet
            int count = Dispatch.get(sheets, "Count").getInt();
            System.out.println(count);
            if (1 < count) {
                sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[]{new Integer(2)}, new int[1]).toDispatch();
            } else {
                sheet = Dispatch.get(excel, "ActiveSheet").toDispatch();
            }
            Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
            Dispatch.put(pageSetup, "Orientation", new Variant(2)); // Variant(2)横向打印
            // 设置边距
            Dispatch.put(pageSetup, "CenterVertically", true);
            // Dispatch.put(pageSetup, "LeftMargin", 0);
            // Dispatch.put(pageSetup, "RightMargin", 0);
            Dispatch.put(pageSetup, "TopMargin", 10);
            Dispatch.put(pageSetup, "BottomMargin", 10);
            Dispatch.put(pageSetup, "PrintGridlines", true);
            // 设置打印纸张
            // Dispatch.put(pageSetup, "PaperSize", 8);
            // 设置缩放
            // Dispatch.put(pageSetup, "Zoom", 49);
            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[]{new Variant(0), // PDF格式=0
                    pdfFile, new Variant(xlTypePDF) // 0=标准 (生成的PDF图片不会变模糊)
            // 1=最小文件
            // (生成的PDF图片糊的一塌糊涂)
            }, new int[1]);
            long end = System.currentTimeMillis();
            logger.info("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {
            // TODO: handle exception
            logger.info("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(excel, "Close", new Variant(false));
            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
        }
    }


    /**
     * ppt转化成PDF
     */
    private void pptToPDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch ppt = new Dispatch();
        try {
            logger.info("进入转换PDF程序");
            ComThread.InitSTA(true);
            app = new ActiveXComponent("KWPP.Application");
            // app.setProperty("Visible", false);
            logger.info("开始转化PPT为PDF...");
            long start = System.currentTimeMillis();
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
                    // false, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{pdfFile, new Variant(ppSaveAsPDF)}, new int[1]);
            long end = System.currentTimeMillis();
            logger.info("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {
            // TODO: handle exception
            logger.info("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(ppt, "Close");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
            // 如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
        }
    }


    private void imgToPDF(String imgFilePath, String pdfFilePath) {
        File file = new File(imgFilePath);
        if (file.exists()) {
            Document document = null;
            FileOutputStream fos = null;
            try {
                // 读取一个图片
                Image image = Image.getInstance(imgFilePath);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                int i = 0;
                while (imageHeight > 500 || imageWidth > 500) {
                    image.scalePercent(100 - i);
                    i++;
                    imageHeight = image.getScaledHeight();
                    imageWidth = image.getScaledWidth();
                }
                image.setAlignment(Image.ALIGN_CENTER);
                // 文档页面宽高为图片宽高
                Rectangle rect = new Rectangle(imageWidth, imageHeight);
                document = new Document(rect);
                // 读取文件流,创建可读写的文件
                fos = new FileOutputStream(pdfFilePath);
                PdfWriter.getInstance(document, fos);
                // 设置文档边距
                document.setMargins(0, 0, 0, 0);
                // 打开文档
                document.open();
                // 插入一个图片
                document.add(image);
            } catch (DocumentException de) {
                System.out.println(de.getMessage());
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

追风落叶乔木生

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值