java利用poi 把ppt转化为图片,
导入jar包:
poi-3.8.jar
poi-ooxml-3.9.jar
poi-scratchpad-3.8.jar
代码:
1 package test4; 2 3 import java.awt.Dimension; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 10 import org.apache.poi.hslf.model.TextRun; 11 import org.apache.poi.hslf.usermodel.RichTextRun; 12 import org.apache.poi.hslf.usermodel.SlideShow; 13 14 import java.awt.Color; 15 import java.awt.Graphics2D; 16 import java.awt.geom.Rectangle2D; 17 import java.awt.image.BufferedImage; 18 19 public class PptToJpg_poi { 20 public static void main(String[] args) { 21 // 读入PPT文件 22 File file = new File("C:\\Users\\Administrator\\Desktop\\pptToJpg\\test8.pptx"); 23 doPPTtoImage(file); 24 } 25 26 public static boolean doPPTtoImage(File file) { 27 boolean isppt = checkFile(file); 28 if (!isppt) { 29 System.out.println("The image you specify don\'t exit!"); 30 return false; 31 } 32 try { 33 FileInputStream is = new FileInputStream(file); 34 SlideShow ppt = new SlideShow(is); 35 is.close(); 36 Dimension pgsize = ppt.getPageSize(); 37 org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides(); 38 for (int i = 0; i < slide.length; i++) { 39 TextRun[] truns = slide[i].getTextRuns(); 40 for (int k = 0; k < truns.length; k++) { 41 RichTextRun[] rtruns = truns[k].getRichTextRuns(); 42 for (int l = 0; l < rtruns.length; l++) { 43 rtruns[l].setFontIndex(1); 44 rtruns[l].setFontName("宋体"); 45 } 46 } 47 BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, 48 BufferedImage.TYPE_INT_RGB); 49 Graphics2D graphics = img.createGraphics(); 50 graphics.setPaint(Color.BLUE); 51 graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); 52 slide[i].draw(graphics); 53 // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径 54 File path = new File("C:/Users/Administrator/Desktop/pptToJpg/images"); 55 if (!path.exists()) { 56 path.mkdir(); 57 } 58 // 可测试多种图片格式 59 // FileOutputStream out = new FileOutputStream(path + "/" + (i + 1) + ".jpg"); 60 // javax.imageio.ImageIO.write(img, "jpeg", out); 61 FileOutputStream out = new FileOutputStream(path + "/" + (i + 1) + ".jpg"); 62 javax.imageio.ImageIO.write(img, "png", out); 63 out.close(); 64 } 65 System.out.println("success!!"); 66 return true; 67 } catch (FileNotFoundException e) { 68 System.out.println(e); 69 } catch (IOException e) { 70 71 } 72 return false; 73 } 74 75 // function 检查文件是否为PPT 76 public static boolean checkFile(File file) { 77 boolean isppt = false; 78 String filename = file.getName(); 79 String suffixname = null; 80 if (filename != null && filename.indexOf(".") != -1) { 81 suffixname = filename.substring(filename.lastIndexOf(".")); 82 if (suffixname.equals(".ppt") || suffixname.equals(".pptx")) { 83 isppt = true; 84 } 85 return isppt; 86 } else { 87 return isppt; 88 } 89 } 90 91 }
亲测有效
版权声明:本文为haw2106原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。