office各种文件转图片

这是一个Java工具类,用于将PDF、DOC和PPT文件转换为图片。它使用Apache POI、ICEpdf和Jacob库来处理不同类型的文件,转换过程中涉及文件读取、图像处理和保存。此外,还包含一个文本文件转图片的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;



/**
 * 各种文件转图片工具类
 * @author yangcheng.ai
 *
 */
public class ImageUtil {
    
    private static Logger log = LoggerFactory.getLogger(ImageUtil.class);
    
    public static Map<String, String> dirMap = new HashMap<String, String>();
    
    
    /**
     * 获取PDF文件转成图片后的数量
     * @param pdfPath
     * @return
     */
    public static Integer getPdfFileSize(String pdfPath){
        Integer size = 0;
        try {
            File file = new File(pdfPath);  
            RandomAccessFile raf = new RandomAccessFile(file, "r");  
            FileChannel channel = raf.getChannel();  
            MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,  
                    0, channel.size());  
            PDFFile pdffile = new PDFFile(buf);
            size = pdffile.getNumPages();
        } catch (Exception e) {
            log.error("文件读取失败!");
            e.printStackTrace();
        }
        return size;
    }

    /**
     * PDF转JPG
     * @param pdfPath
     * @return
     */
    public static String pdfToJpg(String pdfPath){
        boolean checkStatus = false;
        String picPath = pdfPath.split("\\.")[0];
        File dir = new File(picPath);
        if(!dir.exists()){
            dir.mkdir();
            checkStatus = true;
            log.info(pdfPath + "目标文件不存在,准备生成...");
        }else{
            File pdfFile = new File(pdfPath);
            if((pdfFile.lastModified() - dir.lastModified()) > 0){
                checkStatus = true;
                deleteFile(dir);
                log.info(pdfPath + "目标文件有修改,准备生成...");
            }
        }
        
        if(checkStatus){
            int i = 0;
            try {
                Document document = new Document();
                try {
                    document.setFile(pdfPath);
                } catch (Exception e) {
                    //部分ICEPDF无法解析的则使用这个方法解析
                    File file = new File(pdfPath);  
                    RandomAccessFile raf = new RandomAccessFile(file, "r");  
                    FileChannel channel = raf.getChannel();  
                    MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());  
                    PDFFile pdffile = new PDFFile(buf);  
                    
                    //获得图片页数  
                    Integer countpage = pdffile.getNumPages();  
                    for (int j = 1; j <= countpage; j++) {  
                        PDFPage page = pdffile.getPage(j);  
                        Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()), ((int) page.getBBox().getHeight()));  
                        int n = 2;  
                        Image img = page.getImage(rect.width * n, rect.height * n, rect, null, true, true);  
                        BufferedImage tag = new BufferedImage(rect.width * n, rect.height * n, BufferedImage.TYPE_INT_RGB);  
                        tag.getGraphics().drawImage(img, 0, 0, rect.width * n, rect.height * n, null);  
                        
                        FileOutputStream out = new FileOutputStream(picPath + "/" + j + ".png");  
                        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
                        JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);  
                        param2.setQuality(1f, true);  
                        encoder.setJPEGEncodeParam(param2);  
                        encoder.encode(tag);  
                        out.close();  
                    }  
                    channel.close();  
                    raf.close();  
                }
                
                float scale = 2.5f;//缩放比例
                float rotation = 0f;//旋转角度
                int size = document.getNumberOfPages();
                for(i = 0; i < size; i++){
                    BufferedImage image = (BufferedImage)document.getPageImage(i, GraphicsRenderingHints.SCREEN,
                            Page.BOUNDARY_CROPBOX, rotation, scale);
                    RenderedImage rendImage = image;
                    
                    File file = new File(picPath + "/" + (i + 1) + ".jpg");
                    ImageIO.write(rendImage, "png", file);
                    image.flush();
                    log.info("生成第" + i + "页成功。");
                }
                document.dispose();
            } catch (Exception e) {
                log.error("生成第" + i + "页失败。");
                e.printStackTrace();
            }
            log.info("PDF转换成图片成功!");
        }
        return picPath;
    }
    
    /**
     * doc转换为pdf
     * @param docPath
     * @return
     */
    public static String wordToPdf(String docPath){    
        boolean checkStatus = false;
        String pdfPath = docPath.split("\\.")[0] + ".pdf";
        File pdfFile = new File(pdfPath);
        if(!pdfFile.exists()){
            checkStatus = true;
            log.info(docPath + "目标文件不存在,准备生成...");
        }else{
            File docFile = new File(docPath);
            if((docFile.lastModified() - pdfFile.lastModified()) > 0){
                checkStatus = true;
                deleteFile(pdfFile);
                log.info(docPath + "目标文件有修改,准备生成...");
            }
        }
        
        if(checkStatus){
            ComThread.InitMTA(true);
            log.info("启动Word...");      
            long start = System.currentTimeMillis();      
            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", docPath, false, true).toDispatch();  
                log.info("打开文档..." + docPath);  
                log.info("转换文档到PDF..." + pdfPath);      
                Dispatch.call(doc, "SaveAs", pdfPath, 17);      
                long end = System.currentTimeMillis();      
                log.info("转换完成..用时:" + (end - start) + "ms.");  
            } catch (Exception e) {      
                log.error("========Error:文档转换失败:" + e.getMessage());      
            } finally {
                if(doc != null){
                    Dispatch.call(doc,"Close");  
                    log.error("关闭文档");  
                }
                if (app != null){
                    app.invoke("Quit", new Variant[] {});
                }
            }  
            //如果没有这句话,winword.exe进程将不会关闭  
            ComThread.Release();
        }else{
            log.info("目标文件已存在,无需生成...");
        }
        
        return pdfPath;
    }
    
    /**
     * 获取PPT文件转成图片后的数量
     * @param pdfPath
     * @return
     */
    public static Integer getPptFileSize(String pptPath){
        SlideShow ppt = null;
        try {
            ppt = new SlideShow(new HSLFSlideShow(pptPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ppt.getSlides().length;
    }
    
    /**
     * ppt转pdf
     * @param pptPath
     */
    public static String pptToPdf(String pptPath){
        boolean checkStatus = false;
        String pdfPath = pptPath.split("\\.")[0] + ".pdf";
        File pdfFile = new File(pdfPath);
        if(!pdfFile.exists()){
            checkStatus = true;
            log.info(pptPath + "目标文件不存在,准备生成...");
        }else{
            File pptFile = new File(pptPath);
            if((pptFile.lastModified() - pdfFile.lastModified()) > 0){
                checkStatus = true;
                deleteFile(pdfFile);
                log.info(pptPath + "目标文件有修改,准备生成...");
            }
        }
        
        if(checkStatus){
            ComThread.InitMTA(true);
            log.info("启动PPT...");      
            long start = System.currentTimeMillis();      
            ActiveXComponent app = new ActiveXComponent("KWPP.Application");   
            Dispatch ppts = app.getProperty("Presentations").toDispatch();   
            log.info("打开PPT");
            log.info("转换PPT到PDF..." + pdfPath);
            Dispatch ppt = Dispatch.call(ppts, "Open", pptPath, true, true).toDispatch();  
            Dispatch.call(ppt, "SaveAs", pdfPath, new Variant(32));
            long end = System.currentTimeMillis();      
            log.info("转换完成..用时:" + (end - start) + "ms.");
            if(ppt != null){
                Dispatch.call(ppt, "Close");
                app.invoke("Quit");
            }
            ComThread.Release();
        }else{
            log.info("目标文件已存在,无需生成...");
        }
        return pdfPath;
    }
    
    /**
     * 删除文件
     * @param fileName
     * @return
     */
    public static boolean deleteFile(File file) {
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.info("删除单个文件" + file.getName() + "成功!");
                return true;
            } else {
                log.info("删除单个文件" + file.getName() + "失败!");
                return false;
            }
        } else {
            log.info("删除单个文件失败:" + file.getName() + "不存在!");
            return false;
        }
    }
    
    /**
     * 文本文件转图片
     * @param txtPath
     */
    public static void txtToJpg(String txtPath) {  
        boolean checkStatus = false;
        String picPath = txtPath.split("\\.")[0];
        File picFile = new File(picPath);
        if(!picFile.exists()){
            picFile.mkdir();
            checkStatus = true;
            log.info(txtPath + "目标文件不存在,准备生成...");
        }else{
            File txtFile = new File(txtPath);
            if((txtFile.lastModified() - picFile.lastModified()) > 0){
                checkStatus = true;
                deleteFile(picFile);
                log.info(txtPath + "目标文件有修改,准备生成...");
            }
        }
        
        if(checkStatus){
            String content = null;  
            try {  
                FileOutputStream t = new FileOutputStream(picPath + "/1.jpg");
                // 创建图片    
                BufferedImage image = new BufferedImage(1200, 1000, BufferedImage.TYPE_INT_BGR);    
                Graphics g = image.getGraphics();    
                g.setClip(0, 0, 1200, 1000);    
                g.setColor(Color.white);    
                g.fillRect(0, 0, 1200, 1000);// 先用黑色填充整张图片,也就是背景    
                g.setColor(Color.black);// 在换成黑色    
                g.setFont(new Font("微软雅黑", Font.PLAIN, 20));// 设置画笔字体    
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(txtPath),"gbk"));  
                int i=0;
                while ((content = br.readLine()) != null) {  
                    g.drawString(content, 0, (25 * i+20)+40);
                    i++;
                }  
                g.dispose();
                JPEGImageEncoder coder=JPEGCodec.createJPEGEncoder(t);  
                coder.encode(image);
                    t.close();
                    log.info("文本文件转换成功...");
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }else{
            log.info("文本文件转换成功...");
        }
    }  
    
    /**
     * 部分ICEPDF无法解析的则使用这个方法解析
     * @param pdfPath
     * @return
     */
    public static String pdfToJpgByView(String pdfPath) {  
        String picPath = pdfPath.split("\\.")[0];
        //创建图片文件夹  
        File dirfile = new File(picPath);  
        if(!dirfile.exists()){  
            dirfile.mkdirs();  
            try {  
                File file = new File(pdfPath);  
                RandomAccessFile raf = new RandomAccessFile(file, "r");  
                FileChannel channel = raf.getChannel();  
                MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());  
                PDFFile pdffile = new PDFFile(buf);  
                
                //获得图片页数  
                Integer countpage = pdffile.getNumPages();  
                for (int i = 1; i <= countpage; i++) {  
                    PDFPage page = pdffile.getPage(i);  
                    Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()), ((int) page.getBBox().getHeight()));  
                    int n = 2;  
                    Image img = page.getImage(rect.width * n, rect.height * n, rect, null, true, true);  
                    BufferedImage tag = new BufferedImage(rect.width * n, rect.height * n, BufferedImage.TYPE_INT_RGB);  
                    tag.getGraphics().drawImage(img, 0, 0, rect.width * n, rect.height * n, null);  
                    
                    FileOutputStream out = new FileOutputStream(picPath + "/" + i + ".png");  
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
                    JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);  
                    param2.setQuality(1f, true);  
                    encoder.setJPEGEncodeParam(param2);  
                    encoder.encode(tag);  
                    out.close();  
                }  
                channel.close();  
                raf.close();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        return picPath;  
          
    }      

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值