Java如何將PPT的幻燈片轉換為圖片?

2019-10-16 22:28:24

在Java程式設計中,如何將PPT的幻燈片轉換為圖片?

注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並全部匯入 。

需要匯入全部包,如下圖所示 -

以下是使用Java將PPT的幻燈片轉換為圖片的程式。

package com.yiibai;

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 java.util.List;

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 {

        // creating an empty presentation
        File file = new File("addingimage.pptx");
        XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));

        // getting the dimensions and size of the slide
        Dimension pgsize = ppt.getPageSize();
        List<XSLFSlide> slide = ppt.getSlides();
        BufferedImage img = null;

        for (int i = 0; i < slide.size(); i++) {
            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
            slide.get(i).draw(graphics);
        }
        // creating an image file as output
        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();
    }
}

執行上面範例程式碼,得到以下結果 -

Image successfully created

這就建立一個PPT檔案:addingimage.pptx了,如下所示 -