Tuesday, 20 July 2021

[Java] Get the position of text in PowerPoint slides

Here is a PowerPoint slide and there is a English word called test in it. Now I want to get its location using Java codes. Through a lot of tests, I used a free third-party library called Free Spire.Presentation for Java to do it.


About Free Spire.Presentation for Java

Free Spire.Presentation for Java is a professional PowerPoint API that enables developers to create, read, write, convert and save PowerPoint documents in Java Applications. As an independent Java library, you only need to it without installing Microsoft PowerPoint on the system.

Dependency

First of all, we need to create a development environment by downloading and installing JDK and Intellij IDEA. Then get the package of library from the E-iceblue official website, find Spire.Presentation.jar in the “lib” folder. Finally, manually add it to IDEA through several steps as the following screenshot shows.

Of course, there is the other method to add it to IDEA. Create a Maven project in IDEA, and type the following codes in the pom.xml file. Finally, click the button “Import Changes”.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Using the code

Free Spire.Presentation for Java not only supports getting the x and y coordinates of the location relative

to slide, but also can print out the x and y coordinates of the location relative to shape.

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 {
//Create a Presentation instance
Presentation ppt = new Presentation();
//Load a PowerPoint document
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);
//Get the first shape
IAutoShape shape = (IAutoShape)slide.getShapes().get(0);
//Get location of text in the shape
Point2D location =shape.getTextFrame().getTextLocation();

//Print out the x and y coordinates of the location relative to slide
String point1="Text's position relative to Slide: x= "+location.getX()+" y = "+location.getY();
System.out.println(point1);

//Print out the x and y coordinates of the location relative to shape
String point2 = "Text's position relative to shape: x= " + (location.getX() - shape.getLeft()) + " y = " + (location.getY() - shape.getTop());
System.out.println(point2);
}
}

Output




No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...