java實現ppt/pptx轉圖片,轉pdf的兩種方式之一 poi

poi的實現方式是分步實現的,並不能直接將ppt,pptx轉爲pdf.

首先是maven依賴

1.pom.xm需要引入的依賴

 <!--poi依賴-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.18</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.18</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlgraphics</groupId>
            <artifactId>batik-bridge</artifactId>
            <version>1.12</version>
        </dependency>

2.相關工具類封裝

2.1 ppt轉png,以及png轉pdf的導包部分全部在這。

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xslf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;

2.2 ppt轉png的方法

    /**
     * ppt轉爲圖片列表
     * @param pptFile 在(服務器)本地的ppt文件 比如:123.ppt
     * @return 轉換後的圖片集合
     */
public List<File> ppt2Png(File pptFile) {
        List<File> pngFileList = new ArrayList<>();
        long startTime = System.currentTimeMillis();

        FileInputStream is = null;
        // 將ppt文件轉換成每一幀的圖片
        HSLFSlideShow ppt = null;

        try {
            ZipSecureFile.setMinInflateRatio(-1.0d);
            is = new FileInputStream(pptFile);
            ppt = new HSLFSlideShow(is);
            int idx = 1;

            Dimension pageSize = ppt.getPageSize();
            double image_rate = 1.0;
            int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth());
            int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight());

            for (HSLFSlide slide : ppt.getSlides()) {
                BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight));
                graphics.scale(image_rate, image_rate);

                //防止中文亂碼
                for (HSLFShape shape : slide.getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape hslfTextShape = (HSLFTextShape) shape;
                        for (HSLFTextParagraph hslfTextParagraph : hslfTextShape) {
                            for (HSLFTextRun hslfTextRun : hslfTextParagraph) {
                                hslfTextRun.setFontFamily("宋體");
                            }
                        }
                    }
                }

                FileOutputStream out = null;
                try {
                    slide.draw(graphics);
                    File pngFile = new File(pptFile.getPath().replace(".ppt", String.format("-%04d.png", idx++)));
                    out = new FileOutputStream(pngFile);
                    ImageIO.write(img, "png", out);
                    pngFileList.add(pngFile);
                } catch (Exception e) {
                    LOGGER.error("ppt2Png exception", e);
                } finally {
                    try {
                        if (out != null) {
                            out.flush();
                            out.close();
                        }

                        if (graphics != null) {
                            graphics.dispose();
                        }

                        if (img != null) {
                            img.flush();
                        }
                    } catch (IOException e) {
                        LOGGER.error("ppt2Png close exception", e);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("ppt2Png exception", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (ppt != null) {
                    ppt.close();
                }
            } catch (Exception e) {
                LOGGER.error("ppt2Png exception", e);
            }
        }
        long endTime = System.currentTimeMillis();
        LOGGER.info("ppt2Png的時間:{}", endTime - startTime);
        return pngFileList;
    }

2.3 pptx轉png

public List<File> pptx2Png(File pptxFile) {
        List<File> pngFileList = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        FileInputStream is = null;
        // 將ppt文件轉換成每一幀的圖片
        XMLSlideShow pptx = null;

        try {
            ZipSecureFile.setMinInflateRatio(-1.0d);
            is = new FileInputStream(pptxFile);
            pptx = new XMLSlideShow(is);
            int idx = 1;

            Dimension pageSize = pptx.getPageSize();
            double image_rate = 1.0;
            int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth());
            int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight());

            for (XSLFSlide xslfSlide : pptx.getSlides()) {
                BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight));
                graphics.scale(image_rate, image_rate);

                //防止中文亂碼
                for (XSLFShape shape : xslfSlide.getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape xslfTextShape = (XSLFTextShape) shape;
                        for (XSLFTextParagraph xslfTextParagraph : xslfTextShape) {
                            for (XSLFTextRun xslfTextRun : xslfTextParagraph) {
                                xslfTextRun.setFontFamily("宋體");
                            }
                        }
                    }
                }

                FileOutputStream out = null;
                try {
                    xslfSlide.draw(graphics);
                    File pngFile = new File(pptxFile.getPath().replace(".pptx", String.format("-%04d.png", idx++)));
                    out = new FileOutputStream(pngFile);
                    ImageIO.write(img, "png", out);
                    pngFileList.add(pngFile);
                } catch (Exception e) {
                    LOGGER.error("pptx2Png exception", e);
                } finally {
                    try {
                        if (out != null) {
                            out.flush();
                            out.close();
                        }

                        if (graphics != null) {
                            graphics.dispose();
                        }

                        if (img != null) {
                            img.flush();
                        }
                    } catch (IOException e) {
                        LOGGER.error("pptx2Png close exception", e);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("pptx2Png exception", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (pptx != null) {
                    pptx.close();
                }
            } catch (Exception e) {
                LOGGER.error("pptx2Png exception", e);
            }
        }
        long endTime = System.currentTimeMillis();
        LOGGER.info("pptx2Png耗時:{}", endTime - startTime);
        return pngFileList;
    }

2.4 png轉pdf

/**
     * 
     * @param pngFiles 上面方法轉換的圖片集合
     * @param pdfFilePath 生成pdf的指定路徑
     * @return
     */
    public File png2Pdf(List<File> pngFiles, String pdfFilePath) {
        Document document = new Document();
        File inPdfFile = null;
        long startTime = System.currentTimeMillis();
        try {
            String inFilePath = pdfFilePath.replace(".pdf", ".in.pdf");
            inPdfFile = new File(inFilePath);
            PdfWriter.getInstance(document, new FileOutputStream(inPdfFile));
            document.open();

            pngFiles.forEach(pngFile -> {
                try {
                    Image png = Image.getInstance(pngFile.getCanonicalPath());
                    png.scalePercent(50);
                    document.add(png);
                } catch (Exception e) {
                    LOGGER.error("png2Pdf exception", e);
                }
            });
            document.close();

            // 添加水印
            boolean ret = PDFWatermarkUtil.addWatermark(inFilePath, pdfFilePath, watermarkPath);
            if (ret) {
                File pdfFile = new File(pdfFilePath);
                return pdfFile;
            }
        } catch (Exception e) {
            LOGGER.error(String.format("png2Pdf %s exception", pdfFilePath), e);
        } finally {
            if (document.isOpen()) {
                document.close();
            }
            if (inPdfFile != null) {
                inPdfFile.delete();
            }
            long endTime = System.currentTimeMillis();
            LOGGER.info("png2Pdf耗時:{}", endTime - startTime);
        }

        return null;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章