AutoFit Text or Shape in PowerPoint in Java

·

2 min read

When we enter text in the predefined shapes in PowerPoint, if the text is too long, it may overflow the shape and make the whole document look untidy. In this article, you will learn how to automatically shrink text to fit a shape or how to automatically resize a shape to fit text by using Free Spire.Presentation for Java.

Import JAR Dependency (2 Methods)

● Download the free library and unzip it, and then add the Spire.Presentation.jar file to your project as dependency.
● Directly add the jar dependency to your maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.presentation.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Sample Code

Free Spire.Presentation for Java offer the IAutoShape.getTextFrame().setAutofitType(TextAutofitType value) to sets text's autofit mode. By setting the value to NORMAL, you can make the text automatically shrinks to fit the shape, and by setting it to SHAPE, the shape size will automatically shrink or expand to fit text.

import com.spire.presentation.*;

import java.awt.geom.Rectangle2D;

public class AutoFitTextOrShape {

    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation presentation = new Presentation();

        //Get the first slide
        ISlide slide = presentation.getSlides().get(0);

        //Add a shape to slide
        IAutoShape textShape1 = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(50,50,200,80));

        //Add text to shape
        textShape1.getTextFrame().setText("In 1928, Auden published his first book of verse, and his collection Poems, published in 1930, which established him as the leading voice of a new generation.");

        //Set the auto-fit type to normal, which means the text automatically shrinks to fit the shape when text overflows the shape
        textShape1.getTextFrame().setAutofitType(TextAutofitType.NORMAL);

        //Add another shape to slide
        IAutoShape textShape2 = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(350, 50, 200, 80));
        textShape2.getTextFrame().setText("Resize shape to fit text.");

        //Set the auto-fit type to shape, which means the shape size automatically decreases or increases to fit text
        textShape2.getTextFrame().setAutofitType(TextAutofitType.SHAPE);

        //Save to file
        presentation.saveToFile("output/AutoFit.pptx", FileFormat.PPTX_2013);
    }
}