精华内容
下载资源
问答
  • 最近做的需求需要实现在线预览ppt的功能,网上查了一遍,比较完美的方案都需要依赖第三方的服务或调用微软的在线接口,由于项目部署内网,同时为了不增加项目的复杂度,最终决定使用纯java实现,依赖 poi 将ppt 成...

            最近做的需求需要实现在线预览ppt的功能,网上查了一遍,比较完美的方案都需要依赖第三方的服务或调用微软的在线接口,由于项目部署内网,同时为了不增加项目的复杂度,最终决定使用纯java实现,依赖 poi 将ppt 转成 png图片,然后再利用 itextpdf 将图片转成 pdf ,最后通过js实现预览。转换后的pdf效果图如下:

            目前存在一个确定是 ppt字体全部统一换成了 宋体 ,以解决中文有些情况下乱码的问题,本来想研究下能不更换字体的方式,但是没时间,暂时就这样了。有解决方案的同学还请赐教。

            下面直接上代码:

            maven 依赖大致如下:

            <!-- excel工具 -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-scratchpad</artifactId>
                <version>4.1.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml-schemas</artifactId>
                <version>4.1.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>ooxml-schemas</artifactId>
                <version>1.4</version>
            </dependency>
    
            <dependency>
                <groupId>fr.opensagres.xdocreport</groupId>
                <artifactId>xdocreport</artifactId>
                <version>2.0.2</version>
            </dependency>
            <!--pdf start-->
            <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>
            <!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
            <dependency>
                <groupId>net.coobird</groupId>
                <artifactId>thumbnailator</artifactId>
                <version>0.4.8</version>
            </dependency>
    
            <!--end-->

     java 工具类

    package com.fmi110.common.utils;
    
    import com.itextpdf.text.BadElementException;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.ruoyi.common.exception.BusinessException;
    import org.apache.commons.io.IOUtils;
    import org.apache.pdfbox.multipdf.PDFMergerUtility;
    import org.apache.poi.hslf.usermodel.*;
    import org.apache.poi.xslf.usermodel.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.CollectionUtils;
    
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.color.ColorSpace;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorConvertOp;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author fmi110
     * @description ppt 转图片;图片转pdf 工具
     * @date 2021/8/19 20:16
     */
    
    public class PPTUtil {
        protected static final Logger log = LoggerFactory.getLogger(PPTUtil.class);
    
        public static int width  = 720;
        public static int height = 540;
    
        public static void PPTtoImage(String filePath, String fileName) throws Exception {
            File f = new File(filePath + fileName);
            if (f.exists()) {
                if (f.getName().endsWith(".pptx") || f.getName().endsWith(".PPTX")) {
                    pptx2Image(filePath, fileName);
                } else {
                    ppt2Image(filePath, fileName);
                }
            } else {
                throw new BusinessException("文档不存在");
            }
        }
    
        /**
         * 将pptx转换为图片,直接保存在内存中,ppt很大时可能会oom!!!
         *
         * @param is ppt 输入流
         * @return
         * @throws IOException
         */
        public static List<byte[]> pptx2Image(InputStream is) throws IOException {
            // 获取系统可用字体
            GraphicsEnvironment e          = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[]            fontNames  = e.getAvailableFontFamilyNames();
            List                availFonts = CollectionUtils.arrayToList(fontNames);
    
            XMLSlideShow ppt      = new XMLSlideShow(is);
            Dimension    pgsize   = ppt.getPageSize();
            int          pageSize = ppt.getSlides().size();
            List<byte[]> imgList  = new ArrayList<>(pageSize);
    
            log.info("ppt 总页数:{}, 尺寸: width={},height={}", pageSize, pgsize.width, pgsize.height);
    
            for (int i = 0; i < pageSize; i++) {
                //防止中文乱码
                for (XSLFShape shape : ppt.getSlides().get(i).getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape tsh = (XSLFTextShape) shape;
                        for (XSLFTextParagraph p : tsh) {
                            for (XSLFTextRun r : p) {
                                String fontFamily = r.getFontFamily();
                                //log.info(">>>>>原始ppt字体:{}", fontFamily);
                                fontFamily = "宋体";
                                //log.info(">>>>>ppt字体修改为:{}", fontFamily);
                                r.setFontFamily(fontFamily);
    //                            if (!availFonts.contains(fontFamily)) {
    //                                fontFamily = "宋体";
    //                                log.info(">>>>>ppt字体修改为:{}", fontFamily);
    //                                r.setFontFamily(fontFamily);
    //                            }
                            }
                        }
                    }
                }
                BufferedImage img      = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D    graphics = img.createGraphics();
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
                // save the output
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                imgList.add(out.toByteArray());
                IOUtils.closeQuietly(out);
            }
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
            return imgList;
        }
    
        /**
         * 将pptx转成图片,保存在同一目录的image目录下
         *
         * @param filePath ppt文件路径
         * @param fileName ppt 文件名
         * @throws IOException
         */
        public static void pptx2Image(String filePath, String fileName) throws Exception {
    
            // 获取系统可用字体
            GraphicsEnvironment e          = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[]            fontNames  = e.getAvailableFontFamilyNames();
            List                availFonts = CollectionUtils.arrayToList(fontNames);
    
            FileInputStream is  = new FileInputStream(filePath + fileName);
            XMLSlideShow    ppt = new XMLSlideShow(is);
    
            Dimension pgsize   = ppt.getPageSize();
            int       pageSize = ppt.getSlides().size();
            log.info("ppt 总页数:{}, 尺寸: width={},height={}", pageSize, pgsize.width, pgsize.height);
    
            for (int i = 0; i < pageSize; i++) {
    
                //防止中文乱码
                for (XSLFShape shape : ppt.getSlides().get(i).getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape tsh = (XSLFTextShape) shape;
                        for (XSLFTextParagraph p : tsh) {
                            for (XSLFTextRun r : p) {
                                String fontFamily = r.getFontFamily();
                                //log.info(">>>>>原始ppt字体:{}", fontFamily);
                                fontFamily = "宋体";
                                //log.info(">>>>>ppt字体修改为:{}", fontFamily);
                                r.setFontFamily(fontFamily);
    //                            if (!availFonts.contains(fontFamily)) {
    //                                fontFamily = "宋体";
    //                                log.info(">>>>>ppt字体修改为:{}", fontFamily);
    //                                r.setFontFamily(fontFamily);
    //                            }
                            }
                        }
                    }
                }
                BufferedImage img      = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D    graphics = img.createGraphics();
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
                // save the output
                String pptname    = fileName.substring(0, fileName.lastIndexOf("."));
                String newimgPath = filePath + "image/" + pptname + "/";
                File   imgPath    = new File(newimgPath);
                if (!imgPath.exists()) {//图片目录不存在则创建
                    imgPath.mkdirs();
                }
                String           file = newimgPath + (i + 1) + ".png";
                FileOutputStream out  = new FileOutputStream(file);
                javax.imageio.ImageIO.write(img, "png", out);
                IOUtils.closeQuietly(out);
            }
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
        }
    
        /**
         * 将ppt转换为图片,直接保存在内存中,ppt很大时可能会oom!!!
         *
         * @param is ppt 输入流
         * @return
         * @throws IOException
         */
        public static List<byte[]> ppt2Image(InputStream is) throws IOException {
            // 获取系统可用字体
            GraphicsEnvironment e          = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[]            fontNames  = e.getAvailableFontFamilyNames();
            List                availFonts = CollectionUtils.arrayToList(fontNames);
    
            HSLFSlideShow ppt      = new HSLFSlideShow(new HSLFSlideShowImpl(is));
            Dimension     pgsize   = ppt.getPageSize();
            int           pageSize = ppt.getSlides().size();
            List<byte[]>  imgList  = new ArrayList<>(pageSize);
    
            log.info("ppt 总页数:{}, 尺寸: width={},height={}", pageSize, pgsize.width, pgsize.height);
    
            for (int i = 0; i < pageSize; i++) {
                //防止中文乱码
                for (HSLFShape shape : ppt.getSlides().get(i).getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape tsh = (HSLFTextShape) shape;
                        for (HSLFTextParagraph p : tsh) {
                            for (HSLFTextRun r : p) {
                                String fontFamily = r.getFontFamily();
                                //log.info(">>>>>原始ppt字体:{}", fontFamily);
                                fontFamily = "宋体";
                                //log.info(">>>>>ppt字体修改为:{}", fontFamily);
                                r.setFontFamily(fontFamily);
    //                            if (!availFonts.contains(fontFamily)) {
    //                                fontFamily = "宋体";
    //                                log.info(">>>>>ppt字体修改为:{}", fontFamily);
    //                                r.setFontFamily(fontFamily);
    //                            }
                            }
                        }
                    }
                }
                BufferedImage img      = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D    graphics = img.createGraphics();
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
                // save the output
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                imgList.add(out.toByteArray());
                IOUtils.closeQuietly(out);
            }
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
            return imgList;
        }
    
        /**
         * 将ppt转成图片,保存在同一目录的image目录下
         *
         * @param filePath ppt文件路径
         * @param fileName ppt 文件名
         * @throws IOException
         */
        public static void ppt2Image(String filePath, String fileName) throws IOException {
            // 获取系统可用字体
            GraphicsEnvironment e          = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[]            fontNames  = e.getAvailableFontFamilyNames();
            List                availFonts = CollectionUtils.arrayToList(fontNames);
    
            HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(filePath + fileName));
    
            Dimension pgsize = ppt.getPageSize();
            for (int i = 0; i < ppt.getSlides().size(); i++) {
                //防止中文乱码
                for (HSLFShape shape : ppt.getSlides().get(i).getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape tsh = (HSLFTextShape) shape;
                        for (HSLFTextParagraph p : tsh) {
                            for (HSLFTextRun r : p) {
                                String fontFamily = r.getFontFamily();
                                //log.info(">>>>>原始ppt字体:{}", fontFamily);
                                fontFamily = "宋体";
                                //log.info(">>>>>ppt字体修改为:{}", fontFamily);
                                r.setFontFamily(fontFamily);
    //                            if (!availFonts.contains(fontFamily)) {
    //                                fontFamily = "宋体";
    //                                log.info(">>>>>ppt字体修改为:{}", fontFamily);
    //                                r.setFontFamily(fontFamily);
    //                            }
    
                            }
                        }
                    }
                }
                BufferedImage img      = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D    graphics = img.createGraphics();
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
    
                // save the output
                String pptname    = fileName.substring(0, fileName.lastIndexOf("."));
                String newimgPath = filePath + "image/" + pptname + "/";
                File   imgPath    = new File(newimgPath);
                if (!imgPath.exists()) {//图片目录不存在则创建
                    imgPath.mkdirs();
                }
                String           file = newimgPath + (i + 1) + ".png";
                FileOutputStream out  = new FileOutputStream(file);
                javax.imageio.ImageIO.write(img, "png", out);
                IOUtils.closeQuietly(out);
                //resizeImage(filename, filename, width, height);
            }
    
        }
    
        /***
         * 功能 :调整图片大小
         * @param srcImgPath 原图片路径
         * @param distImgPath  转换大小后图片路径
         * @param width   转换后图片宽度
         * @param height  转换后图片高度
         */
        public static void resizeImage(String srcImgPath, String distImgPath,
                                       int width, int height) throws IOException {
            File          srcFile = new File(srcImgPath);
            Image         srcImg  = ImageIO.read(srcFile);
            BufferedImage buffImg = null;
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            buffImg.getGraphics().drawImage(
                    srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,
                    0, null);
            ImageIO.write(buffImg, "JPEG", new File(distImgPath));
        }
    
        /**
         * 将图片转换成pdf
         *
         * @return
         * @throws Exception
         */
        public static byte[] img2PDF(List<byte[]> images) throws Exception {
    
    //        Document              doc    = new Document();
    //        Document doc = new Document(PageSize.A4, 0, 0, 36.0F, 36.0F);//普通a4
            com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(0, 0, width, height); // 自定义页面大小
            Document                    doc      = new Document(pageSize, 0, 0, 0, 0);
            log.info(">>>>A4尺寸:width={},height={}", pageSize.getWidth(), pageSize.getHeight());
            ByteArrayOutputStream pdfOut = new ByteArrayOutputStream();
            PdfWriter.getInstance(doc, pdfOut);
            doc.open();
            float scale = pageSize.getWidth() / width;
            for (byte[] image : images) {
                com.itextpdf.text.Image pic = com.itextpdf.text.Image.getInstance(image);
                pic.setScaleToFitLineWhenOverflow(true);
                // pic.scaleAbsolute(width, height);
                pic.scaleToFit(pageSize.getWidth(), height * scale);
                doc.add(pic);
            }
    
            doc.close();
            byte[] pdf = pdfOut.toByteArray();
            IOUtils.closeQuietly(pdfOut);
            return pdf;
        }
    
        /**
         * ppt转化为pdf
         * @param is ppt 输入流
         * @return pdf 字节文件
         * @throws Exception
         */
        public static byte[] ppt2PDF(InputStream is) throws Exception {
            return img2PDF(ppt2Image(is));
        }
        /**
         * pptx转化为pdf
         * @param is pptx 输入流
         * @return pdf 字节文件
         * @throws Exception
         */
        public static byte[] pptx2PDF(InputStream is) throws Exception {
            return img2PDF(pptx2Image(is));
        }
    
        /**
         * 图片转pdf
         *
         * @param img
         * @param descfolder
         * @return
         * @throws Exception
         */
        public static String img2PDF(String imagePath, BufferedImage img, String descfolder) throws Exception {
            String pdfPath = "";
            try {
                //图片操作
                com.itextpdf.text.Image image = null;
                File                    file  = new File(descfolder);
    
                if (!file.exists()) {
                    file.mkdirs();
                }
    
                pdfPath = descfolder + "/" + System.currentTimeMillis() + ".pdf";
                String   type = imagePath.substring(imagePath.lastIndexOf(".") + 1);
                Document doc  = new Document(null, 0, 0, 0, 0);
    
                //更换图片图层
                BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
                bufferedImage.getGraphics().drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
                bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB), null).filter(bufferedImage, null);
    
                //图片流处理
                doc.setPageSize(new com.itextpdf.text.Rectangle(bufferedImage.getWidth(), bufferedImage.getHeight()));
                log.info(bufferedImage.getWidth() + "()()()()()" + bufferedImage.getHeight());
                ByteArrayOutputStream out  = new ByteArrayOutputStream();
                boolean               flag = ImageIO.write(bufferedImage, type, out);
                byte[]                b    = out.toByteArray();
                image = com.itextpdf.text.Image.getInstance(b);
    
                //写入PDF
                log.info("写入PDf:" + pdfPath);
                FileOutputStream fos = new FileOutputStream(pdfPath);
                PdfWriter.getInstance(doc, fos);
                doc.open();
                doc.add(image);
                doc.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            return pdfPath;
        }
    
        public static void mergePDF(String[] files, String desfolder, String mergeFileName) throws Exception {
    
            PDFMergerUtility mergePdf = new PDFMergerUtility();
    
            for (String file : files) {
                if (file.toLowerCase().endsWith("pdf"))
                    mergePdf.addSource(file);
            }
    
            mergePdf.setDestinationFileName(desfolder + "/" + mergeFileName);
            mergePdf.mergeDocuments();
            log.info("merge over");
    
        }
    
        public static void main(String[] args) throws Exception {
            // 读入PPT文件
            String filePath = "D:/test/";
            String fileName = "docker.pptx";
    
            List<byte[]> images = pptx2Image(new FileInputStream(new File(filePath + fileName)));
            // 输出图片
            for (int i = 1; i <= images.size(); i++) {
                String path = filePath + i + ".png";
                FileOutputStream output = new FileOutputStream(path);
                IOUtils.write(images.get(i-1), output);
                IOUtils.closeQuietly(output);
            }
    
            // 输出pdf
            byte[]           pdf = pptx2PDF(new FileInputStream(new File(filePath + fileName)));
            FileOutputStream out = new FileOutputStream("D:/test/docker.pdf");
            IOUtils.write(pdf, out);
            IOUtils.closeQuietly(out);
    
        }
    
    }
    

    执行工具类main函数后测试的效果:

    参考文章:

    https://blog.csdn.net/huoji555/article/details/88339039

    https://www.cnblogs.com/chenpi/p/5534595.html

    https://zhanglf.blog.csdn.net/article/details/106853803?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-18.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-18.control

    展开全文
  • java ppt/pptx转图片所需要的全部jar包 ,2003,2007,的都可以
  • 主要为大家详细介绍了java实现PPT转PDF出现中文乱码问题的解决方法,进行了详细的问题分析,需要的朋友可以参考下
  • Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 POI 操作office需要的jar包: <properties> <poi.version>3.17</...

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。

    POI 操作office需要的jar包:

     <properties>
    		<poi.version>3.17</poi.version>
        </properties>
           <!-- poi office -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>${poi.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-examples</artifactId>
                <version>${poi.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>${poi.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml-schemas</artifactId>
                <version>${poi.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-scratchpad</artifactId>
                <version>${poi.version}</version>
            </dependency>
    

    poi生成的原图清晰度比较有限,所以转高清图的思路是生成图片的时候放大图片。下面是代码的实现。

    package com.gorun.platform.art.common.minio.http;
    
    
    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.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    import org.apache.poi.xslf.usermodel.XMLSlideShow;
    import org.apache.poi.xslf.usermodel.XSLFShape;
    import org.apache.poi.xslf.usermodel.XSLFSlide;
    import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
    import org.apache.poi.xslf.usermodel.XSLFTextRun;
    import org.apache.poi.xslf.usermodel.XSLFTextShape;
    
    public class Ppt {
    
        public static void main(String[] args) {
            File ppt = new File("C:\\Users\\lenovo\\Desktop\\7787.pptx");
            String img = "C:\\Users\\lenovo\\Desktop\\demo";
            System.out.println(converPPTtoImage(ppt,img,"png",8));
        }
    
        /**
         * 将PPT 文件转换成image
         *
         * @param orignalPPTFile    //PPT文件对象 如:d:/demo/demo1.ppt
         * @param targetImageFileDir    //转换后的图片保存路径 如:d:/demo/pptImg
         * @param imageFormatNameString //图片转化的格式字符串 ,如:"jpg"、"jpeg"、"bmp" "png" "gif" "tiff"
         * @param times //生成图片放大的倍数,倍数越高,清晰度越高
         * @return 图片名列表
         */
        public static int converPPTtoImage(File orignalPPTFile,String targetImageFileDir,
                                           String imageFormatNameString, int times) {
    
            //验证图片是否为pptx格式
            if(!checkIsPPTFile(orignalPPTFile)){
                System.out.print("转换文件必须是pptx!");
                return 0;
            }
            List<String> list = new ArrayList<String>();
            FileInputStream is = null ;
            int imgCount = 0;
            File imgFile = new File(targetImageFileDir);
            //如果没有文件夹就创建文件夹
            createDirIfNotExist(targetImageFileDir);
            try {
                is = new FileInputStream(orignalPPTFile);
                XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
                is.close();
                // 获取大小
                Dimension pgsize = xmlSlideShow.getPageSize();
                // 获取幻灯片
                XSLFSlide[] slides = xmlSlideShow.getSlides().toArray(new XSLFSlide[0]);
                imgCount = slides.length;
                for (int i = 0 ; i < slides.length ; i++) {
                    // 解决乱码问题
                    XSLFShape[] shapes = slides[i].getShapes().toArray(new XSLFShape[0]);
                    for (XSLFShape shape : shapes) {
                        if (shape instanceof XSLFTextShape) {
                            XSLFTextShape sh = (XSLFTextShape) shape;
                            List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                            for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                                List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                                for (XSLFTextRun xslfTextRun : textRuns) {
                                    xslfTextRun.setFontFamily("宋体");
                                }
                            }
                        }
                    }
                    // 创建BufferedImage对象,图像的尺寸为原来的每页的尺寸*倍数times
                    BufferedImage img = new BufferedImage(pgsize.width * times,
                            pgsize.height * times, BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setPaint(Color.white);
                    graphics.scale(times, times);// 将图片放大times倍
                    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,pgsize.height));
                    // 最核心的代码
                    slides[i].draw(graphics);
                    //图片将要存放的路径
                    String absolutePath = imgFile.getAbsolutePath()+"/"+ (i + 1)
                            + "_" + UUID.randomUUID().toString() + "." + imageFormatNameString;
                    File jpegFile = new File(absolutePath);
                    // 图片路径存放
                    list.add((i + 1) + ".jpg");
                    //如果图片存在,则不再生成
                    if (jpegFile.exists()) {
                        continue;
                    }
                    // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
                    FileOutputStream out = new FileOutputStream(jpegFile);
                    // 写入到图片中去
                    ImageIO.write(img, "jpeg", out);
                    out.close();
                }
                System.out.print("PPT转换成图片 成功!");
                return imgCount;
            }
            catch (Exception e) {
                e.printStackTrace();
                System.out.print("PPT转换成图片 发生异常!");
            }
            return imgCount;
        }
    
    
    
        /**
         * 检查是否为ppt文件
         * @param file
         * @return
         */
        public static boolean checkIsPPTFile(File file) {
            boolean isppt = false;
            String filename = file.getName();
            String suffixname = null;
            if (filename != null && filename.indexOf(".") != -1) {
                suffixname = filename.substring(filename.lastIndexOf("."));
                if (".pptx".equals(suffixname)) {
                    isppt = true;
                }
                return isppt;
            } else {
                return isppt;
            }
        }
    
        /**
         * 创建文件如果路径不存在则创建对应的文件夹
         * @param file
         * @return
         */
        public static File createDirIfNotExist(String file) {
            File fileDir = new File(file);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            return fileDir;
        }
    
    }
    
    
    展开全文
  • poi的实现方式是分步实现的,并不能直接将ppt,pptx转为pdf. 首先是maven依赖 1.pom.xm需要引入的依赖 <!--poi依赖--> <dependency> <groupId>org.apache.poi</groupId> <...

    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;
        }

     

    展开全文
  • java实现生成ppt文件

    2020-07-18 08:00:14
    小例子java实现生成,搞了好久才弄出来的!
  • aspose我这里有两种实现方式,一种和poi类似,及通过png图片合成pdf.还有一种是直接生成pdf.这两种我感觉第一种更灵活,因为专程图片后可以对图片处理,比如截图,压缩图片,设置透明度,缩放等等。并且这种处理方式...

    aspose我这里有两种实现方式,一种和poi类似,及通过png图片合成pdf.还有一种是直接生成pdf.这两种我感觉第一种更灵活,因为专程图片后可以对图片处理,比如截图,压缩图片,设置透明度,缩放等等。并且这种处理方式要比直接生成pdf的好像是快点。但是这种快也不是差别很大。

    好了,下面是先准备工作,因为这个aspose需要依赖jar包。aspose.slides-15.9.0.jar,而如果没有word转pdf的可以不用引入第二个 aspose-words-15.8.0-jdk16.jar, 并且这个jar包不是通过maven引入的,虽然maven库里有这个,但是下不下来。需要在pom里做本地jar包引入的配置。

    1.在resources下新建个jar,然后将jar包放在里面。

    2.在pom中配置本地依赖的jar。这样打包也能打到项目中。

     <!--引入本地的office转pdf的破解版aspose jar包-->
            <dependency>
                <groupId>com.aspose</groupId>
                <artifactId>aspose-words</artifactId>
                <version>15.8.0</version>
                <scope>system</scope>
                <systemPath>${project.basedir}/src/main/resources/jar/aspose-words-15.8.0-jdk16.jar</systemPath>
            </dependency>
            <dependency>
                <groupId>com.aspose</groupId>
                <artifactId>aspose.slides</artifactId>
                <version>15.9.0</version>
                <scope>system</scope>
                <systemPath>${project.basedir}/src/main/resources/jar/aspose.slides-15.9.0.jar</systemPath>
            </dependency>
    
    
    
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <includeSystemScope>true</includeSystemScope>
                    </configuration>
                </plugin>
            </plugins>

    3.这两个jar包如果获取?

    链接: https://pan.baidu.com/s/1rxr73vtMIGWBDh2fuQAH9Q   提取码: r646

    链接: https://pan.baidu.com/s/1fdScUhysaATeKwph2HP0Wg 提取码: hbsc

    以上就是准备工作了。下一节贴具体实现

     

    展开全文
  • (一) 简介: 工作中,PowerPoint文档有时需要被转换为PDF/图像文件来存档。...基于上述原因,下面介绍如何使用Free Spire.Presentation for JavaJava中将PowerPoint文档转为图片或PDF。 (二)所...
  • poi与aspose的比较 ...ppt/pptxpng图片阶段:poi或者aspose,其中poi在这个阶段的速度比aspose快很多,但是有一点,就是偶尔会底层报错,但是aspose出错的可能性极低。具体怎末选,看你是看重速度还是上传的成功率
  • java实现在线预览--poi实现word、excel、ppt转html

    万次阅读 多人点赞 2019-07-31 18:39:43
    java实现在线预览- -之poi实现word、excel、ppt转html
  • Entry.java这个类的原理是先通过OfficeToPDF.java把文档成pdf,然后再通过Pdf2Jpg.java这个类把PDF成JPG或者PNG,想成什么格式图片在Pdf2Jpg.java这个类当中设置一下,代码经过测试,完全没有问题,如果碰到...
  • 最近在做的一个项目需要在网页中播放PPT文件,思考良久并没有想出很好的解决方案,最后决定先将PPT文件转换成PDF文件,再嵌入网页中(具体怎么实现在网页中播放PDF文件,网上有很多解决方案,在这里就不再赘述)。...
  • java ppt文件转图片ppt转PDF

    千次阅读 2019-05-17 15:38:08
    先上图,有图有真相.本人亲测,可以通过 因为android没办法直接加载ppt文件,需要借助第三方的软件,比如office,这就涉及一个文件保密的问题,只能使用自己的软件加载,... 1:我这是先把ppt转成一张张图片 ...
  • java实现poi模板生成PPT文件代码:两个迭代版本。java实现poi模板生成PPT文件代码:两个迭代版本。
  • 前言:刚开发出一款应用程序马上就要上线了,可喜可贺,可喜可贺扑面而来的是PC端的需求,新的需求里有好几处是将PPT上传经过处理图片(JPEG, PNG,JPG等格式)保存到服务器待用。第一时间想到的POI,开始写的...
  • 1、新增控制器 ... @ApiOperation("根据课件转化PPT再返回图片数组") @PostMapping("/reviewPPt/{fileId}") public Map<String, Object> reviewPPt(@PathVariable("fileId") Integer fileId) { //...
  • 主要介绍了JavaPPT中添加文本和图片超链接的实现方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
  • Java实现PPT转化为PDF

    2021-05-17 10:23:22
    这篇文章主要为大家详细介绍了java实现PPT转化为PDF的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 文章目录前言一、pandas是什么?二、使用步骤1.引入库2.读入数据总结 前言 提示:这里可以添加本文...
  • 我用的是Apache POI实现PPT转图片,Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 有兴趣的可以查看官方文档:Apache POI官网 ...
  • 支持word、excel、ppt、wps、txt等多种格式pdf、并支持pdfword。个人感觉非常好用。
  • java实现在线预览--poi实现word excel ppt转html
  • 在网上搜索到的方法都是将字体的样式统一设置为"宋体",不太合适业务,而且在linux环境下也会乱码,有没有大神解决了这个问题啊??求指教
  • 如题! POI就不用说了,我自己测试过...但只支持单线程,即同一时刻只能转换一个PPT,而PPT转换成图片的过程又有点稍长, 故满足不了需求 哪位大虾做过这个事情,给点指导撒 小白用户,第一次来,没有可恶的C币,呜呜~
  • java 使用jacob实现word、excle、ppt转pdf IDEA Maven 微服务项目示例 示例: 步骤: 1.jarcob jar包、插件下载 SaveAsPDFandXPS 下载地址: http://www.microsoft.com/zh-cn/download/details.aspx?id=7 (若访问...
  • 前: 后: 如何解决效果问题,求大神解决!!!!!!!!!..................................
  •       ...Spire.Presentation for Java:同样的转换过程很慢、最要命的是免费版只能转换ppt的前几页,后面的页面会无情的告诉你:该付费了少年、但是清晰度还可以。 思考
  • 一、PPT转图片可行方案探索历程 PPT转图片方案 方案具体步骤及分析 已放弃方案 poi(失真度太高);Aspose直接转图片(收费,效果较好,备选);微软Office Online(需要基于Windows...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 8,863
精华内容 3,545
关键字:

java实现ppt转图片

java 订阅