class="MsoNormal">本篇文章将介绍通过Java程序来读取PPT幻灯片中的文本及图片的方法。读取图片时,可读取文档中的所有图片,也可以读取指定幻灯片当中的图片。
?
工具:
Jar文件获取及导入:
方法1:官网下载jar文件包。下载后,解压文件,并在java程序中导入lib文件夹下的Spire.Presentation.jar文件。
方法2:可通过maven仓库导入到maven项目。
?
测试文档:
?
import com.spire.presentation.IAutoShape; import com.spire.presentation.ISlide; import com.spire.presentation.ParagraphEx; import com.spire.presentation.Presentation; import java.io.FileWriter; public class ExtractText { public static void main(String[]args) throws Exception{ //加载测试文档 Presentation ppt = new Presentation(); ppt.loadFromFile("test.pptx"); StringBuilder buffer = new StringBuilder(); //遍历文档中的幻灯片,提取文本 for (Object slide : ppt.getSlides()) { for (Object shape : ((ISlide) slide).getShapes()) { if (shape instanceof IAutoShape) { for (Object tp : ((IAutoShape) shape).getTextFrame().getParagraphs()) { buffer.append(((ParagraphEx) tp).getText()); } } } } //保存到文本文件 FileWriter writer = new FileWriter("ExtractText.txt"); writer.write(buffer.toString()); writer.flush(); writer.close(); } }
?文本读取结果:
?
import com.spire.presentation.Presentation; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class ExtractAllImgs { public static void main(String[] args) throws Exception { //加载文档 Presentation ppt = new Presentation(); ppt.loadFromFile("test.pptx"); //提取文档中的所有图片 for (int i = 0; i < ppt.getImages().getCount(); i++) { BufferedImage image = ppt.getImages().get(i).getImage(); ImageIO.write(image, "PNG", new File(String.format("AllImage-%1$s.png", i))); } } }
?
import com.spire.presentation.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class ExtractImgsInSpecifiedSlide { public static void main(String[]args) throws Exception{ //加载文档 Presentation ppt = new Presentation(); ppt.loadFromFile("test.pptx"); //获取第2张幻灯片 ISlide slide = ppt.getSlides().get(1); //提取图片 for(int i = 0; i< slide.getShapes().getCount(); i++) { IShape shape = slide.getShapes().get(i); if(shape instanceof SlidePicture) { SlidePicture pic = (SlidePicture) shape; BufferedImage image = pic.getPictureFill().getPicture().getEmbedImage().getImage(); ImageIO.write(image, "PNG", new File(String.format("extractImageinslide-%1$s.png", i))); } if(shape instanceof PictureShape) { PictureShape ps = (PictureShape) shape; BufferedImage image = ps.getEmbedImage().getImage(); ImageIO.write(image, "PNG", new File(String.format("extractImageinslide-%1$s.png", i))); } } } }
?
?图片读取结果:
?
(本文完)
?