首页 > 编程 > Java > 正文

如何使用Java读取PPT文本和图片

2019-11-26 08:49:37
字体:
来源:转载
供稿:网友

前言

本篇文章将介绍通过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)));   }  } }}

图片读取结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表