本篇文章将介绍通过Java程序来读取PPT幻灯片中的文本及图片的方法。读取图片时,可读取文档中的所有图片,也可以读取指定幻灯片当中的图片。
工具:
Free Spire.Presentation for Java(免费版)
IntelliJ IDEA
Jar文件获取及导入:
方法1:官网下载jar文件包。下载后,解压文件,并在java程序中导入lib文件夹下的Spire.Presentation.jar文件。
方法2:可通过maven仓库导入到maven项目。
Java代码示例
测试文档 如下:
【示例1】读取PPT中的文本
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(); } }
文本读取结果:
【示例2】读取PPT中的所有图片
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))); } } }
【示例3】读取指定幻灯片中的图片
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))); } } } }
图片读取结果:
(本文完)
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶(hù)
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)