Wednesday, 16 September 2020

Replace Text and an Image in PowerPoint in Java

It’s time-consuming to create a beautiful PowerPoint document completely through Java program. Here I recommend a method which not only saves time but also can achieve a perfect result. First, you need to use Microsoft Office to create a PowerPoint template, and then replace the text and pictures in the template through Java program.

Before typing codes, please make sure you have a required test environment which includes Intellij Idea2019.1, JDK 1.8.0 and Spire.Presentation.jar.

How to add Spire.Presentation.jar to your project?

Method 1: Download Free Spire.Presentation for Java package from the link, unzip it and find Spire.Presentation.jar in the “lib” folder, and add it into IDEA as a dependency.

Method 2: add Spire.Presentation.jar in your maven-based project using the following repository and dependency information.

<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>2.6.1</version>

    </dependency>

</dependencies>

Creating a PowerPoint template

Here I use Microsoft Office to create a PowerPoint template with text and an image. Meanwhile, we can set the font, font size and color of the text in advance so that the new text that is replaced into the document can retain the desired format.

 

Replace Text in PPT

Free Spire.Presentation for Java provides the replaceText method to replace text in PPT.

The following are some steps to achieve the result.

Step 1: load the PowerPoint template and get the first slide

Step 2: create a Map object and add the original text and text that is replaced into the file to the Map.

Step 3: using the replaceText method to replace text and save the resulting file.

import com.spire.presentation.*;
import java.util.HashMap;
import java.util.Map;

public class ReplaceText {
   
public static void main(String[] args) throws Exception {
       
//create a Presentation object
       
Presentation presentation = new Presentation();
       
//load the template file
       
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//get the first slide
       
ISlide slide= presentation.getSlides().get(0);
       
//create a Map object
       
Map<String, String> map = new HashMap<String, String>();
       
//add several pairs of keys and values to the map
       
map.put("# Name#","the Forbidden city");
        map.put(
"# Place#","Beijing,China");
        String description =
"The Forbidden City is the imperial palace of the Ming and Qing Dynasties in China. " +
               
"It is located in the center of the central axis of Beijing and is the essence of ancient Chinese palace architecture. " +
               
"The Forbidden City is centered on three halls, covering an area of 720,000 square meters, " +
               
"with a construction area of about 150,000 square meters, more than 70 large and small palaces, " +
               
"and more than 9,000 houses. It is one of the largest and best-preserved ancient wooden structure buildings in the world.";
        map.put(
"# Introduction#",description);
       
//replace text in the slide
       
replaceText(slide,map);
       
//save to another file
       
presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
    }
   
/*
     * Replace text within a slide
     * @param slide Specifies the slide where the replacement happens
     * @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
     */
   
public static void replaceText(ISlide slide, Map<String, String> map) {
       
for (Object shape : slide.getShapes()
        ) {
           
if (shape instanceof IAutoShape) {

               
for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
                ) {
                    ParagraphEx paragraphEx =(ParagraphEx)paragraph;
                   
for (String key : map.keySet()
                    ) {
                       
if (paragraphEx.getText().contains(key)) {
                            paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
                        }
                    }
                }
            }
        }
    }
}

Output


Replace an Image in PPT

Free Spire.Presentation for Java also supports replacing an image in PPT through the following code snippets.

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;
import javax.imageio.ImageIO; import java.awt.image.BufferedImage;
import java.io.FileInputStream;
public class ReplaceImage {
   
public static void main(String[] args) throws Exception {
       
//create a Presentation object
       
Presentation presentation= new Presentation();
       
//load the sample PowerPoint file
       
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\ReplaceText.pptx");
       
//add an image to the image collection
       
String imagePath ="C:\\Users\\Test1\\Desktop\\palace.png";
        BufferedImage bufferedImage = ImageIO.read(
new FileInputStream(imagePath));
        IImageData image = presentation.getImages().append(bufferedImage);
       
//get the shape collection from the first slide
       
ShapeCollection shapes = presentation.getSlides().get(0).getShapes();
       
//loop through the shape collection
       
for (int i = 0; i < shapes.getCount(); i++) {
           
//determine if a shape is a picture
           
if (shapes.get(i) instanceof SlidePicture) {
               
//fill the shape with a new image
               
((SlidePicture)shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
               
break;  }
        }
       
//save to file
       
presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);
    }
}

Output


Conclusion

Through the tutorial, we can easily create a beautiful PowerPoint document by using replace text and

pictures in the template through Java program. If there is any question about code snippets, please leave

a note on our Forum.

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...