使用Apache POI将ppt截屏成png格式(+背景和图片)

推荐一篇很好的Apache POI文章:使用POI操作PPT文档
本代码的大部分内容参考自这里。
改进:多渲染了ppt背景颜色和ppt背景图片。
有时候,不得不承认。。。Java在做应用上还是很好的,可用的库太多了。
另:貌似ppt比pdf好解析多了,不知道ppt格式M$有没有申请专利,反正pptx已经能解析了。

package extract;

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.FileOutputStream;

import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;

import util.Const;

import bean.PPTBean;

/**
* 将每个slide转化成png格式加以保存
*
* @author liheyuan
*
*/
public class SaveSlideAsPNG {

/**
* 将一个ppt的所有slide转化为png,存储
*
* @param ss
* @param bean
*/
public static void convertAllSlides(HSLFSlideShow ss, PPTBean bean) {
SlideShow ppt = new SlideShow(ss);
Dimension pgsize = ppt.getPageSize();
Slide[] slide = ppt.getSlides();

// 存放png的根目录
String dir_root = Const.SLIDE_PNG_DIR + "/" + bean.getPptID() + "/";
File file = new File(dir_root);
file.mkdirs();

for (int i = 0; i < slide.length; i++) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
// clear the drawing area
int backgroundColor = slide[i].getColorScheme()
.getBackgroundColourRGB();
graphics.setPaint(new Color(backgroundColor));
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,
pgsize.height));

// render the background
slide[i].getBackground().draw(graphics);
// render the content
slide[i].draw(graphics);

String filename = dir_root + (i + 1) + ".png";

FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
javax.imageio.ImageIO.write(img, "png", out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
// Nothing
}
}
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *