【功能需求】

下面是一个PowerPoint示例文档的幻灯片截图,现想通过后台调用Java代码来获取其中文本“时间的价值”的位置信息。

【解决方案】

一款名为Free Spire.Presentation for Java的第三方控件可以实现上述操作。可在其官网E-iceblue上获取产品包,或直接在项目的pom.xml中引用以下代码来导入相关Jar包。

com.e-iceblue https://repo.e-iceblue.cn/repository/maven-public/ e-iceblue spire.presentation.free 3.9.0

【代码示例】

Free Spire.Presentation for Java支持获取指定文本相对于幻灯片或所在形状的位置信息,以下是代码操作步骤。

  • 创建Presentation实例
  • 使用Presentation.loadFromFile()方法加载PowerPoint示例文档
  • 使用Presentation.getSlides().get()方法获取指定幻灯片
  • 使用(IAutoShape)ISlide.getShapes().get()方法获取指定形状
  • 使用IAutoShape.getTextFrame().getTextLocation()方法获取形状中文本的位置
  • 输出文本位置的x和y坐标信息

import com.spire.presentation.IAutoShape; import com.spire.presentation.ISlide; import com.spire.presentation.Presentation; import java.awt.geom.Point2D; public class GetPositionOfText { public static void main(String[] args) throws Exception { //创建Presentation实例 Presentation ppt = new Presentation(); //加载PowerPoint文档 ppt.loadFromFile("C:\Users\Test1\Desktop\sample.pptx"); //获取第一张幻灯片 ISlide slide = ppt.getSlides().get(0); //获取第一个形状 IAutoShape shape = (IAutoShape)slide.getShapes().get(0); //获取形状中文本的位置 Point2D location =shape.getTextFrame().getTextLocation(); //打印文本位置(相对于幻灯片)的x和y坐标 String point1="文本位置(相对于幻灯片): x= "+location.getX()+" y = "+location.getY(); System.out.println(point1); //打印文本位置(相对于形状)的x和y坐标 String point2 = "文本位置(相对于形状): x= " + (location.getX() - shape.getLeft()) + " y = " + (location.getY() - shape.getTop()); System.out.println(point2); } }

运行结果图