java poi ppt操作示例

Posted 阿西八

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java poi ppt操作示例相关的知识,希望对你有一定的参考价值。

poi3.9版本,官网  http://poi.apache.org/slideshow/how-to-shapes.html

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.AutoShape;
import org.apache.poi.hslf.model.Fill;
import org.apache.poi.hslf.model.Freeform;
import org.apache.poi.hslf.model.HeadersFooters;
import org.apache.poi.hslf.model.Hyperlink;
import org.apache.poi.hslf.model.Line;
import org.apache.poi.hslf.model.Picture;
import org.apache.poi.hslf.model.Shape;
import org.apache.poi.hslf.model.ShapeTypes;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.SlideMaster;
import org.apache.poi.hslf.model.Table;
import org.apache.poi.hslf.model.TableCell;
import org.apache.poi.hslf.model.TextBox;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.PictureData;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.hslf.usermodel.SoundData;

public class PPTParseUtil {
	public static void main(String[] args) throws IOException {
		SlideShow ppt = new SlideShow();

		// 设置标题,底部信息
		// presentation-scope headers / footers
		HeadersFooters hdd = ppt.getSlideHeadersFooters();
		hdd.setSlideNumberVisible(true);
		hdd.setFootersText("Created by POI-HSLF");

		// add first slide
		Slide s1 = ppt.createSlide();

		// add second slide
		Slide s2 = ppt.createSlide();
		// retrieve page size. Coordinates are expressed in points (72 dpi)
		java.awt.Dimension pgsize = ppt.getPageSize();
		int pgx = pgsize.width; // slide width
		int pgy = pgsize.height; // slide height

		// set new page size
		ppt.setPageSize(new java.awt.Dimension(1024, 768));
		// save changes
		FileOutputStream out = new FileOutputStream("E:\\logs\\slideshow.ppt");

		// get slides
		Slide[] slide = ppt.getSlides();
		for (int i = 0; i < slide.length; i++) {
			Shape[] sh = slide[i].getShapes();
			for (int j = 0; j < sh.length; j++) {
				// name of the shape
				String name = sh[j].getShapeName();

				// shapes‘s anchor which defines the position of this shape in
				// the slide
				java.awt.Rectangle anchor = sh[j].getAnchor();

				if (sh[j] instanceof Line) {
					Line line = (Line) sh[j];
					// work with Line
				} else if (sh[j] instanceof AutoShape) {
					AutoShape shape = (AutoShape) sh[j];
					// work with AutoShape
				} else if (sh[j] instanceof TextBox) {
					TextBox shape = (TextBox) sh[j];
					// work with TextBox
				} else if (sh[j] instanceof Picture) {
					Picture shape = (Picture) sh[j];
					// work with Picture
				}
			}
		}

		// Drawing a shape on a slide
		Slide slide2 = ppt.createSlide();

		// set slide title
		TextBox title = slide2.addTitle();
		title.setText("Hello, World!");
		// Line shape
		Line line = new Line();
		line.setAnchor(new java.awt.Rectangle(50, 50, 100, 20));
		line.setLineColor(new Color(0, 128, 0));
		line.setLineStyle(Line.LINE_DOUBLE);
		slide2.addShape(line);

		// TextBox
		TextBox txt = new TextBox();
		txt.setText("Hello, World!");
		txt.setAnchor(new java.awt.Rectangle(300, 100, 300, 50));

		// use RichTextRun to work with the text format
		RichTextRun rt = txt.getTextRun().getRichTextRuns()[0];
		rt.setFontSize(32);
		rt.setFontName("Arial");
		rt.setBold(true);
		rt.setItalic(true);
		rt.setUnderlined(true);
		rt.setFontColor(Color.red);
		rt.setAlignment(TextBox.AlignRight);

		slide2.addShape(txt);

		// create shapes of arbitrary geometry
		java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
		path.moveTo(100, 100);
		path.lineTo(200, 100);
		path.curveTo(50, 45, 134, 22, 78, 133);
		path.curveTo(10, 45, 134, 56, 78, 100);
		path.lineTo(100, 200);
		path.closePath();

		Freeform shape = new Freeform();
		shape.setPath(path);
		slide2.addShape(shape);

		// Autoshape
		// 32-point star
		AutoShape sh1 = new AutoShape(ShapeTypes.Star32);
		sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200));
		sh1.setFillColor(Color.red);
		slide2.addShape(sh1);

		// Trapezoid
		AutoShape sh2 = new AutoShape(ShapeTypes.Trapezoid);
		sh2.setAnchor(new java.awt.Rectangle(150, 150, 100, 200));
		sh2.setFillColor(Color.blue);
		slide2.addShape(sh2);

		// work with pictures
		// extract all pictures contained in the presentation
		PictureData[] pdata = ppt.getPictureData();
		for (int ii = 0; ii < pdata.length; ii++) {
			PictureData pict = pdata[ii];

			// picture data
			byte[] data = pict.getData();

			int type = pict.getType();
			String ext;
			switch (type) {
			case Picture.JPEG:
				ext = ".jpg";
				break;
			case Picture.PNG:
				ext = ".png";
				break;
			case Picture.WMF:
				ext = ".wmf";
				break;
			case Picture.EMF:
				ext = ".emf";
				break;
			case Picture.PICT:
				ext = ".pict";
				break;
			default:
				continue;
			}
			FileOutputStream out2 = new FileOutputStream("pict_" + ii + ext);
			out2.write(data);
			out2.close();

		}

		// add a new picture to this slideshow and insert it in a new slide
		int idx = ppt.addPicture(new File("E:\\logs\\clock.png"), Picture.PNG);

		Picture pict = new Picture(idx);

		// set image position in the slide
		pict.setAnchor(new java.awt.Rectangle(100, 100, 300, 200));

		Slide slide3 = ppt.createSlide();
		slide3.addShape(pict);

		// This slide has its own background.
		// Without this line it will use master‘s background.
		slide3.setFollowMasterBackground(false);
		Fill fill = slide3.getBackground().getFill();
		int idx1 = ppt.addPicture(new File("E:\\logs\\clock.png"), Picture.PNG);
		fill.setFillType(Fill.FILL_PATTERN);
		fill.setPictureData(idx1);

		// create bulleted lists

		TextBox shape1 = new TextBox();
		RichTextRun rt1 = shape1.getTextRun().getRichTextRuns()[0];
		shape1.setText("January\r" + "February\r" + "March\r" + "April");
		rt1.setFontSize(42);
		rt1.setBullet(true);
		rt1.setBulletOffset(0); // bullet offset
		rt1.setTextOffset(50); // text offset (should be greater than bullet
								// offset)
		rt1.setBulletChar(‘\u263A‘); // bullet character
		slide3.addShape(shape1);

		shape1.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); // position
																	// of the
																	// text box
																	// in the
																	// slide
		slide3.addShape(shape1);

		// now retrieve pictures containes in the first slide and save them on
		// disk
		slide3 = ppt.getSlides()[0];
		Shape[] sh3 = slide3.getShapes();
		for (int i2 = 0; i2 < sh3.length; i2++) {
			if (sh3[i2] instanceof Picture) {
				Picture pict1 = (Picture) sh3[i2];
				PictureData pictData = pict1.getPictureData();
				byte[] data = pictData.getData();
				int type = pictData.getType();
				if (type == Picture.JPEG) {
					FileOutputStream out3 = new FileOutputStream("slide0_" + i2
							+ ".jpg");
					out3.write(data);
					out3.close();
				} else if (type == Picture.PNG) {
					FileOutputStream out4 = new FileOutputStream("slide0_" + i2
							+ ".png");
					out4.write(data);
					out4.close();
				}
			}
		}

		// modify background of a slide master
		SlideMaster master = ppt.getSlidesMasters()[0];

		Fill fill1 = master.getBackground().getFill();
		int idx11 = ppt
				.addPicture(new File("E:\\logs\\clock.png"), Picture.PNG);
		fill1.setFillType(Fill.FILL_PICTURE);
		fill1.setPictureData(idx11);

		// read hyperlinks from a slide show
		Slide[] slide1 = ppt.getSlides();
		for (int j = 0; j < slide1.length; j++) {

			// read hyperlinks from the text runs
			TextRun[] txt1 = slide1[j].getTextRuns();
			if (txt1 == null || txt1.length == 0) {
				continue;
			}
			for (int k = 0; k < txt1.length; k++) {
				String text = txt1[k].getText();
				Hyperlink[] links = txt1[k].getHyperlinks();
				if (links != null)
					for (int l = 0; l < links.length; l++) {
						Hyperlink link = links[l];
						String title1 = link.getTitle();
						String address = link.getAddress();
						String substring = text.substring(link.getStartIndex(),
								link.getEndIndex() - 1); // in ppt end index is
															// inclusive
						System.out.println(title1 + address + substring);
					}
			}

			// in PowerPoint you can assign a hyperlink to a shape without text,
			// for example to a Line object. The code below demonstrates how to
			// read such hyperlinks
			Shape[] sh = slide1[j].getShapes();
			for (int k = 0; k < sh.length; k++) {
				Hyperlink link = sh[k].getHyperlink();
				if (link != null) {
					String title1 = link.getTitle();
					String address = link.getAddress();
					System.out.println(title1 + address);
				}
			}
		}

		// table data
		String[][] data = { { "INPUT FILE", "NUMBER OF RECORDS" },
				{ "Item File", "11,559" }, { "Vendor File", "300" },
				{ "Purchase History File", "10,000" },
				{ "Total # of requisitions", "10,200,038" } };

		// 创建表格
		Slide slide11 = ppt.createSlide();
		// create a table of 5 rows and 2 columns
		Table table = new Table(5, 2);
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[i].length; j++) {
				TableCell cell = table.getCell(i, j);
				cell.setText(data[i][j]);

				RichTextRun rt11 = cell.getTextRun().getRichTextRuns()[0];
				rt11.setFontName("Arial");
				rt11.setFontSize(10);

				cell.setVerticalAlignment(TextBox.AnchorMiddle);
				cell.setHorizontalAlignment(TextBox.AlignCenter);
			}
		}

		// set table borders
		Line border = table.createBorder();
		border.setLineColor(Color.black);
		border.setLineWidth(1.0);
		table.setAllBorders(border);

		// set width of the 1st column
		table.setColumnWidth(0, 300);
		// set width of the 2nd column
		table.setColumnWidth(1, 150);

		slide11.addShape(table);
		table.moveTo(100, 100);

		// retrieve embedded sounds 获取语音信息
		SoundData[] sound = ppt.getSoundData();
		for (int i = 0; i < sound.length; i++) {
			// save *WAV sounds on disk
			if (sound[i].getSoundType().equals(".WAV")) {
				FileOutputStream out1 = new FileOutputStream(
						sound[i].getSoundName());
				out1.write(sound[i].getData());
				out1.close();
			}
		}

		ppt.write(out);
		out.close();
	}
}


1)如果是创建新的PPT文档,直接使用SlideShow和Slide类就可以,其中SlideShow表示PPT文档,Slide表示某一张幻灯片
如下代码创建空的PPT文档:

Java代码  技术分享
  1. SlideShow ppt = new SlideShow();  
  2. Slide[] slides = ppt.getSlides();  
  3. assertTrue(slides.length == 0);  
  4. savePPTFile(ppt);  
  5.    
  6. private void savePPTFile(SlideShow ppt) throws Exception{  
  7.          FileOutputStream out = new FileOutputStream("ppt测试.ppt");  
  8.     ppt.write(out);  
  9.     out.close();  
  10. }  

 2)设置母版,这样后续的新建幻灯片都将使用母版的字体,背景等设置

Java代码  技术分享
  1. SlideShow ppt = new SlideShow();  
  2. //设置幻灯片大小  
  3. ppt.setPageSize(new Dimension(760,600));  
  4. SlideMaster master = ppt.getSlidesMasters()[0];         
  5. //设置母板背景,支持多种图片格式  
  6. int picIndex = ppt.addPicture(new File("background.png"), Picture.PNG);  
  7. Picture background = new Picture(picIndex);  
  8. //设置图片位置  
  9. background.setAnchor(new java.awt.Rectangle(0, 0, ppt.getPageSize().width  
  10.                                                , ppt.getPageSize().height));  
  11. master.addShape(background);  

3)创建幻灯片并插入文本

Java代码  技术分享
  1. SlideShow ppt = new SlideShow();  
  2. Slide newSlide = ppt.createSlide();  
  3.    
  4. //添加幻灯片标题  
  5. TextBox title = newSlide.addTitle();  
  6. RichTextRun titleRun = title.getTextRun().getRichTextRuns()[0];  
  7. titleRun.setFontColor(Color.RED);  
  8. title.setText("ppt测试");  
  9.    
  10. //添加文本框  
  11. TextBox txt = new TextBox();  
  12. RichTextRun richTextRun = txt.getTextRun().getRichTextRuns()[0];  
  13. richTextRun.setFontColor(Color.BLUE);    
  14. //setText参数字符串可以包含回车、换行符,但是最后一行不能以\r\n结尾,否则设置的格式没有效果(v3.5)  
  15. richTextRun.setText("这里可以换行\r\n第二行文本");           
  16. txt.setAnchor(new java.awt.Rectangle(50,150,400,400));  
  17. newSlide.addShape(txt);  
  18.    
  19. savePPTFile(ppt);  

4)插入图片,支持多种格式

Java代码  技术分享
  1. SlideShow ppt = new SlideShow();  
  2. Slide newSlide = ppt.createSlide();  
  3. int picIndex = ppt.addPicture(new File("图片.jpg"), Picture.JPEG);  
  4. Picture jpg = new Picture(picIndex);  
  5.    
  6. //set image position in the slide  
  7. jpg.setAnchor(new java.awt.Rectangle(360, 200, 280, 260));  
  8.    
  9. newSlide.addShape(jpg);  
  10. savePPTFile(ppt);  

5)插入表格(v3.5)

Java代码  技术分享
  1. SlideShow ppt = new SlideShow();  
  2. Slide slide = ppt.createSlide();  
  3.    
  4. String[][] datas = {  
  5.     {"序号", "姓名","年龄"},  
  6.     {"1", "张三","30"},  
  7.     {"2", "李四","27"},  
  8. };  
  9.    
  10. //create a table of 3 rows and 3 columns  
  11. Table table = new Table(3, 3);  
  12.    
  13. for (int i = 0; i < datas.length; i++) {  
  14.     for (int j = 0; j < datas[i].length; j++) {  
  15.         TableCell cell = table.getCell(i, j);  
  16.    
  17.         RichTextRun rt = cell.getTextRun().getRichTextRuns()[0];  
  18.         rt.setFontName("宋体");  
  19.         rt.setFontSize(12);  
  20.    
  21.         cell.setVerticalAlignment(TextBox.AnchorMiddle);  
  22.         cell.setHorizontalAlignment(TextBox.AlignCenter);  
  23.         cell.setText(datas[i][j]);  
  24.    
  25.         if(i == 0){//首行背景设置为灰色  
  26.              cell.setFillColor(Color.GRAY);  
  27.         }                   
  28.     }  
  29. }  
  30.    
  31. Line border = table.createBorder();  
  32. border.setLineColor(Color.black);  
  33. border.setLineWidth(2.0);  
  34. table.setAllBorders(border);   
  35.    
  36. slide.addShape(table);  
  37. table.moveTo(160,260);  
  38. savePPTFile(ppt);  

 6)如果是读取已存在的PPT文档则还要用到HSLFSlideShow,下面代码将PPT文件导出为图片(png)格式,如果幻灯片上有中文字符则这些字符的字体需要修改为支持中文的字体(宋体等),否则导出的图片的中文字符不能正常显示

Java代码  技术分享
  1. SlideShow ppt = new SlideShow(new HSLFSlideShow("PPT测试.ppt"));  
  2. Dimension pgsize = ppt.getPageSize();  
  3. Slide[] slide = ppt.getSlides();  
  4.    
  5. for (int i = 0; i < slide.length; i++) {  
  6.     BufferedImage img = new BufferedImage(pgsize.width, pgsize.height  
  7.                                                , BufferedImage.TYPE_INT_RGB);  
  8.     Graphics2D graphics = img.createGraphics();  
  9.     //clear the drawing area  
  10.     graphics.setPaint(Color.white);  
  11.     graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));  
  12.    
  13.     //render  
  14.     slide[i].draw(graphics);  
  15.    
  16.     FileOutputStream out = new FileOutputStream("slide-"  + (i+1) + ".png");  
  17.     javax.imageio.ImageIO.write(img, "png", out);  
  18.     out.close();  

7)提取PPT文档信息

Java代码  技术分享
  1. SlideShow ppt = new SlideShow(new HSLFSlideShow("PPT测试.ppt"));  
  2. Slide[] slides = ppt.getSlides();  
  3. //提取文本信息           
  4. for (Slide each : slides) {  
  5.     System.out.println(each.getTitle()) ;  
  6.     TextRun[] textRuns = each.getTextRuns();  
  7.     for (int i=0 ;i< textRuns.length; i++ ) {  
  8.         System.out.println(textRuns[i].getText());  
  9.         RichTextRun[] richTextRuns = textRuns[i].getRichTextRuns();  
  10.         for (int j = 0; j < richTextRuns.length; j++) {  
  11.             System.out.println(richTextRuns[j].getText());  
  12.         }  
  13.     }  
  14. }  
  15. //提取所有JPEG图片  
  16. PictureData[] picDatas = ppt.getPictureData();  
  17. for (int i=0;i<picDatas.length;i++) {  
  18.     if(picDatas[i].getType() == Picture.JPEG){  
  19.         FileOutputStream out = new FileOutputStream("jpg_" + i + ".jpg");  
  20.         ppt.write(out);  
  21.         out.close();  
  22.     }  
  23. }  

8)设置PPT文档摘要信息(文档点击鼠标右键查看属性)

Java代码  技术分享
    1. HSLFSlideShow hslf = HSLFSlideShow.create();  
    2. DocumentSummaryInformation dsi= hslf.getDocumentSummaryInformation();     
    3. SummaryInformation si= hslf.getSummaryInformation();     
    4.    
    5. dsi.setCompany("yourCompany");    
    6. dsi.setCategory("ppt测试");     
    7. si.setAuthor("yourName");     
    8. si.setTitle("标题");    
    9.    
    10. SlideShow ppt = new SlideShow(hslf);  
    11. savePPTFile(ppt);  




以上是关于java poi ppt操作示例的主要内容,如果未能解决你的问题,请参考以下文章

java poi 操作ppt

java poi ppt 接口的基本操作

java poi xwpf操作word生成一个表格怎么合并单元格,求大神指导!

java使用poi读取ppt文件

java读取txt/pdf/xls/xlsx/doc/docx/ppt/pptx

关于java使用POI导出ppt ,其中表格setText 失败问题