码迷,mamicode.com
首页 > 编程语言 > 详细

java-使用Jacob实现office转换成pdf

时间:2019-04-17 17:57:26      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:模糊   book   pdf   activex   rac   servlet   erp   click   flush   

 

 

 

技术图片
package net.nblh.utils;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

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

public class Word2PdfUtil {

    private static final int ppSaveAsPDF = 32;

    static final int wdDoNotSaveChanges = 0;// 不保存待定的更改
    static final int wdFormatPDF = 17;// word转PDF 格式

    /**
     * 文档转pdf转png
     * @param source 源文件
     */
    public static int execuConvert(String source) {
        
        String ext = source.substring(source.lastIndexOf("."));
        String tar = source.replace(ext, ".pdf");
        File file = new File(tar);
        
        if (file.exists()) {
            //pdf文件已转换,直接转png
            return pdf2pngByFile(tar);
        }

        // 示例
//        String source = "D:\\2017\\庭审案件材料一.doc";
//        String target = "D:\\2018\\庭审案件材料一.pdf";

        if (!checkAvailable(source,tar)) {
            return 0;
        }

//        String t = setPdfType(source, target);
        
        String suffixStr = getSuffix(source);
        if (".doc".equals(suffixStr) || ".docx".equals(suffixStr)) {
            return word2pdf(source, tar);
        } else if(".pptx".equals(suffixStr) || ".ppt".equals(suffixStr)){
             return ppt2pdf(source, tar);
        } else if(".xls".equals(suffixStr) || ".xlsx".equals(suffixStr)){
            return xls2Pdf(source, tar);
        } else {
            System.out.println("无法转换此文件格式");
        }
        return 0;

    }

    public static int word2pdf(String source, String target) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);

            Dispatch docs = app.getProperty("Documents").toDispatch();

            doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();
            File tofile = new File(target);
            File dirPath = new File(getPath(target));
            if (tofile.exists()) {
                tofile.delete();
            } else if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            Dispatch.call(doc, "SaveAs", target, wdFormatPDF);
//            Dispatch.call(doc, "SAs", target, wdFormatPDF);

            Dispatch.call(doc, "Close", false);
            doc = null;

            app.invoke("Quit", wdDoNotSaveChanges);
            app = null;
            System.out.println("pdf_ok");
            
            return pdf2pngByFile(target);
        } catch (Exception e) {
            return 0;
        } finally {
            if (null != doc) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", wdDoNotSaveChanges);
            }
        }
    }

    /**
     * 检查文件格式,只转换doc ,docx,ppt格式 fileName 文件名
     * 
     * @return
     */
    private static boolean checkFormat(String fileName) {
        if (null == fileName || "".equals(fileName)) {
            return false;
        }

        if (!(fileName.substring(fileName.lastIndexOf(File.separator)).contains("."))) {
            System.out.println("没有指明要转换的文件");
            return false;
        }

        String format = fileName.substring(fileName.lastIndexOf("."));
        if (".doc".equals(format) || ".docx".equals(format) || ".ppt".equals(format) || ".pptx".equals(format)
                || ".xls".equals(format) || ".xlsx".equals(format) || ".dot".equals(format) || ".dotx".equals(format)
                || ".pot".equals(format) || ".potx".equals(format) || ".xlt".equals(format) || "xltx".equals(format)) {

            return true;
        }
        System.out.println("文件格式不合符,无法转换");
        return false;
    }
    
    /**
     * 检查路径是否正确
     * @return
     */
    public static boolean checkAvailable(String source,String target){
        if (isEmpty(source.trim())) {
            System.out.println("源文件路径不存在");
            return false;
        }
        
        if(!source.contains(File.separator) || !source.contains(".")){
            System.out.println("请输入正确的源文件路径,以及源文件名");
            return false;
        }
        
        if(".".equals(getSuffix(source).trim())){
            System.out.println("请输入正确的源文件名");
            return false;
        }
        
        if(isEmpty(target)){
            System.out.println("目标文件路径不存在");
            return false;
        }
        
        if(!target.contains(File.separator) || !target.contains(".")){
            System.out.println("请输入正确的目标文件路径,以及目标文件名");
            return false;
        }
        
        if(!".pdf".equals(getSuffix(target))){
            System.out.println("请正确输入要生成的pdf文件名");
            return false;
        }
        
        return true;
    }

    /**
     * 截取文件全路径,不包括文件名 F:/snd/down/ceshi/
     */
    private static String getPath(String fileName) {
        if (null != fileName || !"".equals(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf(File.separator));
        }
        return "";
    }

    /**
     * 如果目标文件后缀名不是pdf,则强行改为pdf
     */
    private static String setPdfType(String source, String target) {
        // 目标路径包含文件名称
        if (target.substring(target.lastIndexOf(File.separator)).contains(".")) {
            String ext = target.substring(target.lastIndexOf("."));
            String fileName = target.replace(ext, ".pdf");
            return fileName;
        } else {
            // 没有文件名称,只有路径
            return target + getFileName(source) + ".pdf";
        }
    }

    /**
     * 截取文件名 不包含后缀名
     * 
     * @return
     */
    private static String getFileName(String fileName) {
        if (!isEmpty(fileName)) {
            return fileName.substring(fileName.lastIndexOf(File.separator), fileName.lastIndexOf("."));
        }
        return "";
    }
    
    /**
     * 获得后缀名
     * @param fileName
     * @return
     */
    private static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    private static boolean isEmpty(String str) {
        if (null == str || "".equals(str)) {
            return true;
        }
        return false;
    }

    //ppt 转 pdf
    public static int ppt2pdf(String srcFilePath, String pdfFilePath) {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            // 因POWER.EXE的发布规则为同步,所以设置为同步发布
            ppt = Dispatch.call(ppts, "Open", srcFilePath, true, // ReadOnly
                    true, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            
            File dirPath = new File(getPath(pdfFilePath));
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            Dispatch.call(ppt, "SaveAs", pdfFilePath, ppSaveAsPDF); // ppSaveAsPDF为特定值32
            System.out.println("pdf转换完成!");
            
            return pdf2pngByFile(pdfFilePath); // set flag true;
        } catch (ComFailException e) {
            System.out.println(e.toString());
            return 0;
        } catch (Exception e) {
            System.out.println(e.toString());
            return 0;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }

    // EXCEL转PDF
    public static int xls2Pdf(String inFilePath, String outFilePath) {
        ActiveXComponent ax = null;
        Dispatch excels = null;
        Dispatch excel = null;
        try {
            
            ax = new ActiveXComponent("Excel.Application");
            ComThread.InitSTA();
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            excels = ax.getProperty("Workbooks").toDispatch();
            
            File dirPath = new File(getPath(outFilePath));
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[] { inFilePath, new Variant(false), new Variant(false) }, new int[9])
                    .toDispatch();

            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    outFilePath, new Variant(0) }, new int[1]);// 0=标准
                                                                // (生成的PDF图片不会变模糊)
                                                                // 1=最小文件
                                                                // (生成的PDF图片糊的一塌糊涂)

            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[] {});
                ax = null;
            }
            System.out.println("pdf转换完成!");
            
            return pdf2pngByFile(outFilePath);
        } catch (Exception es) {
            System.out.println(es.toString());
            return 0;
        } finally {
            ComThread.Release();
        }
    }
    
    /**
     * 本地pdf文件转png 
     */
    public static int pdf2pngByFile(String target){
        String filePath = target;
        Document document = new Document();
//        System.out.println("开始转png");
        try {
            document.setFile(filePath);
            float scale = 1.5f;// 缩放比例(大图)
            // float scale = 0.2f;// 缩放比例(小图)
            float rotation = 0f;// 旋转角度
            int pageSize = document.getNumberOfPages();
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
                        org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
                RenderedImage rendImage = image;
//                try {
//                    File file = new File("D:/fileUpload/ftpDownload/icepdf_a" + i + ".png");
//                    // 这里png作用是:格式是jpg但有png清晰度
//                    ImageIO.write(rendImage, "png", file);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                try {
//                    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
//                    ServletContext servletContext = webApplicationContext.getServletContext();
//                    File contextPath = new File(servletContext.getRealPath("/")); // 项目根目录
//                    File uploadPath = new File(
//                            contextPath.getParentFile().getAbsoluteFile() + File.separator + "uploadFiles"); // 上传图片存放目录
                    File uploadPath = new File(target);
                    String fileName = getPathWithName(target);
                    File file1 = new File(fileName);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
//                    System.out.println("地址=" + uploadPath.getAbsolutePath() + "/icepdf_a" + i + ".png" + "\n");
                    File file = new File(fileName + "\\" + i + ".png");
                    // 这里png作用是:格式是jpg但有png清晰度
                    ImageIO.write(rendImage, "png", file);
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.flush();
            }
            document.dispose();
            System.out.println("png_ok");
            System.out.println("pageSize="+pageSize);
            return pageSize;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return 0;
    }
    
    /**
     * 截取文件全路径,包括文件名,去掉后缀 F:/snd/down/ceshi/aaa
     */
    public static String getPathWithName(String fileName) {
        if (null != fileName || !"".equals(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
        return "";
    }

}
View Code

 

java-使用Jacob实现office转换成pdf

标签:模糊   book   pdf   activex   rac   servlet   erp   click   flush   

原文地址:https://www.cnblogs.com/lijianda/p/10725062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!