文档展示:POI PPT转图片

阅读更多
接上篇 文档展示 PDF转图片
http://zhuyufufu.iteye.com/admin/blogs/2009600

本篇研究使用POI转PPT到图片

参考apache poi api slideshow:
http://poi.apache.org/slideshow/how-to-shapes.html#Render

Export PowerPoint slides into java.awt.Graphics2D

演示代码
package com.zas.ppt.demo;

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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;

public class PPTtoImage {
	static String filePath = "D:\\pdf\\转换用.ppt";
	static String outputFilePath = "D:\\pdf\\ppt\\";

	public static boolean change(File file, File outputFolder) {
		// TODO 校验输入文件是否存在 以及是否为PPT
		try {
			FileInputStream is = new FileInputStream(file);
			SlideShow ppt = new SlideShow(is);
			Dimension pgsize = ppt.getPageSize();
			Slide[] slide = ppt.getSlides();
			for (int indexPPT = 0; indexPPT < slide.length; indexPPT++) {
				System.out.println("第" + indexPPT + "页。");
				TextRun[] truns = slide[indexPPT].getTextRuns();
				for (int indexTestRun = 0; indexTestRun < truns.length; indexTestRun++) {
					RichTextRun[] rtruns = truns[indexTestRun].getRichTextRuns();
					for (int indexRTR = 0; indexRTR < rtruns.length; indexRTR++) {
						rtruns[indexRTR].setFontIndex(1);
						rtruns[indexRTR].setFontName("宋体");
					}
				}
				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);

				Graphics2D graphics = img.createGraphics();
				graphics.setBackground( new Color( 255, 255, 255, 0 ) );
			    graphics.clearRect( 0, 0, pgsize.width, pgsize.height);
				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
				slide[indexPPT].draw(graphics);

				// 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
				FileOutputStream out = new FileOutputStream(outputFolder.getAbsolutePath() + File.separator + (indexPPT + 1) + ".jpg");
				javax.imageio.ImageIO.write(img, "jpeg", out);
				out.close();
				is.close();
			}
			System.out.println("success!!");
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static void main(String[] args) {
		File file = new File(PPTtoImage.filePath);
		File outputFolder = new File(PPTtoImage.outputFilePath);
		if(!outputFolder.exists()){
			outputFolder.mkdirs();
		}
		PPTtoImage.change(file, outputFolder);
	}

}


问题:
  我的测试例子生成的图片没有文字内容

  据说就算生成出图片效果也会失真很多

  打算换个思路:使用OpenOffice将PPT转为PDF

你可能感兴趣的:(POI,PPT,PPT转图片)