java通过poi转换ppt/pptx内容,输出为PNG图片。

POI依赖

maven


        <!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.0.1</version>
        </dependency>

转换[ppt和pptx要分开处理]

  • ppt通过 org.apache.poi.hslf包来处理
  • pptx通过 org.apache.poi.xslf包来处理
  • 直接上代码↓↓↓

import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.xslf.usermodel.*;
import org.junit.jupiter.api.Test;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

/**
 * @author RedRush
 * @date 2022/6/29 17:10
 * @description: ppt转化工具类
 */
public class PPTUtil {

    /**
     * @Author: RedRush
     * @Date:   2022/6/29 22:32
     * @description: ppt/pptx 转换为图片
     */
    @Test
    public void transPPTXToPic(){
        String root = "D:\\work\\Download\\";
//        String fileName = "Test.pptx";
        String fileName = "Test.ppt";
        try {
            if(fileName.toUpperCase().endsWith(".PPTX")){
                transPPTXToPic(root, fileName);
            }else if(fileName.toUpperCase().endsWith(".PPT")){
                transPPTToPic(root, fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // PPT输出为图片 hslf解析
    private void transPPTToPic(String filePath, String fileName){
        // 生成输出
        String outRoot = filePath + fileName.substring(0, fileName.indexOf('.')) + File.separator;
        System.err.printf("图片输出路径为:%s\n", outRoot);
        // 不存在则创建文件夹
        mkdir(outRoot);
        // ppt读取路径
        String pptName = filePath + fileName;
        System.err.printf("PPT读取路径为:%s\n", pptName);
        FileInputStream fis = null;

        try{
            // 获取系统可用字体
            GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontNames  = e.getAvailableFontFamilyNames();

            // 读取ppt
            fis = new FileInputStream(new File(pptName));
            HSLFSlideShow ppt = new HSLFSlideShow(fis);


            /*
             * 解析PPT基本内容
             * */
            Dimension sheet = ppt.getPageSize();
            int width = sheet.width, height = sheet.height;
            List<HSLFSlide> pages = ppt.getSlides();

            System.err.printf("ppt基本信息: 共%s页,尺寸: %s , %s", pages.size(), width, height);

            BufferedImage img      = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D    graphics = img.createGraphics();
            int i = 1;
            // 逐页遍历
            for(HSLFSlide slide : pages){

                // 清空画板
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, width, height));
                slide.draw(graphics);
                // 输出为图片
                File f = new File(outRoot + i++ + ".png");
                System.out.printf("输出图片:%s\n", f.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(f);
                javax.imageio.ImageIO.write(img, "PNG", fos);
                fos.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // PPTX输出为图片 xmls包解析
    private void transPPTXToPic(String filePath, String fileName){
        // 生成输出
        String outRoot = filePath + fileName.substring(0, fileName.indexOf('.')) + File.separator;
        System.err.printf("图片输出路径为:%s\n", outRoot);
        // 不存在则创建文件夹
        mkdir(outRoot);
        // ppt读取路径
        String pptName = filePath + fileName;
        System.err.printf("PPT读取路径为:%s\n", pptName);
        FileInputStream fis = null;

        try{
            // 获取系统可用字体
            GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontNames  = e.getAvailableFontFamilyNames();

            // 读取ppt
            fis = new FileInputStream(new File(pptName));
            XMLSlideShow ppt = new XMLSlideShow(fis);


            /*
            * 解析PPT基本内容
            * */
            Dimension sheet = ppt.getPageSize();
            int width = sheet.width, height = sheet.height;
            int count = ppt.getSlides().size();
            System.err.printf("ppt基本信息: 共%s页,尺寸: %s , %s", count, width, height);


            BufferedImage img      = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D    graphics = img.createGraphics();
            int i = 1;
            // 逐页遍历
            for(XSLFSlide shape : ppt.getSlides()){

                // 清空画板
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, width, height));
                shape.draw(graphics);
                // 输出为图片
                File f = new File(outRoot + i++ + ".png");
                System.out.printf("输出图片:%s\n", f.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(f);
                javax.imageio.ImageIO.write(img, "PNG", fos);
                fos.close();
            }
        }catch (Exception e){
            System.err.println("======ppt转换异常");
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    // 生成文件夹
    private void mkdir(String path){
        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
    }
}

小节

  • poi输出为图片,部分地方输出存在bug,比如图表无法导出(柱形图,饼图之类的),文本框的背景色无法渲染,有些文本在powerpoint里显示正常,但通过poi导出成PNG图片后,可能会超出画布边界,比如某些文本多页面,最后一行导出以后就看不到了。
  • 不过好处在于,poi不需要引入很多第三方的包。凑合凑合用还行。
  • 说句废话,还是用做ppt的电脑直接另存为png/pdf效果最好,字体啊,布局啊也不会乱变。有时候同一个ppt文档,用office做,用wps打开都会有些差异,何况这些代码去处理呢。

你可能感兴趣的:(后端学习整理,java,自用脚本,java,ppt,经验分享,图片导出)