DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Replace Text and Images in PowerPoint in Java

Creating a PowerPoint document from scratch can be quite time-consuming. It is getting even harder if you manage to create a well-designed document completely through java code. Therefore, we recommend pre-designing a template using MS PowerPoint and then replacing the text and images in it using Free Spire.Presentation for Java. By doing so, you can save some time and automate the process to some extend. The following sections will demonstrate the same.

Creating a Template

As shown below, we prepared a simply template that contains one image and several pieces of text. The text has been formatted with font color, font size and font name, so that the new text replaced in the document retains the desired style.

Alt Text

Adding Jar to Project

Step 1. Download Free Spire.Presentation for Java package, unzip it. You’ll find Spire.Presentation.jar file under the lib folder.

Step 2. Create a java project in your IED and add the jar file as a dependency. Here is what it looks like in IntelliJ IDEA.

Alt Text

Using the Code

Part 1. Replace Text

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\\Administrator\\Desktop\\template.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("#cityName#","Chengdu");
        map.put("#location#","Sichuan Province, China");
        String description = "Chengdu, formerly romanized as Chengtu, is a sub-provincial city which serves as the capital "+
                "of China's Sichuan province. It is one of the three most populous cities in Western China . As of 2014, "+
                "the administrative area houses 14,427,500 inhabitants, with an urban population of 10,152,632. At the time "+
                "of the 2010 census, Chengdu was the 5th-most populous agglomeration in China, with 10,484,996 inhabitants "+
                "in the built-up area including Xinjin County and Deyang's Guanghan City.";
        map.put("#description#",description);
        map.put("#popular#","Museum, Landmark, Religious Sites, Architecture, Parks");

        //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)));
                         }
                    }
                }
            }
        }
    }
}

Alt Text

Part 2. Replace Image

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 documenet generted by above code
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\ReplaceText.pptx");

        //add an image to the image collection 
        String imagePath = "C:\\Users\\Administrator\\Desktop\\Chengdu.jpeg";
        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);
            }
        }

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

Alt Text

Top comments (0)