如何使用 Java 将 PPT 幻灯片转换为图片

问题描述

如何使用 Java 将 PPT 幻灯片转换为图片。

解决方案

以下是将 PPT 幻灯片转换为图片的程序。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
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 org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class PptToImage {
   public static void main(String args[]) throws IOException {

      //创建一个空的演示文稿
      File file = new File("addingimage.pptx");
      XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

      //获取幻灯片的尺寸和大小
      Dimension pgsize = ppt.getPageSize();
      XSLFSlide[] slide = ppt.getSlides();
      BufferedImage img = null;

      for (int i = 0; i < slide.length; i++) {
         img = new BufferedImage(pgsize.width, pgsize.height,BufferedImage.TYPE_INT_RGB);
         Graphics2D graphics = img.createGraphics();

         //清除绘图区域
         graphics.setPaint(Color.white);
         graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
         
         //render
         slide[i].draw(graphics);
      }
      //创建图像文件作为输出
      FileOutputStream out = new FileOutputStream("ppt_image.png");
      
      javax.imageio.ImageIO.write(img, "png", out);
      ppt.write(out);
      System.out.println("Image successfully created");
      out.close();
   }
}

输入

幻灯片

输出

幻灯片输出
java_apache_poi_ppt.html