DEV Community

CodeSharing
CodeSharing

Posted on

[Java] Apply Background Image to PowerPoint Slides

When manipulating a Powerpoint document, the background is very important. A unified background image can make the whole document looks cleaner and more attractive. This article will introduce how to apply background image to all slides in a PowerPoint document by using Free Spire.Presentation for Java.

Installation
Method 1: Download the Free Spire.Presentation for Java and unzip it. Then add the Spire.Presentation.jar file to your project as dependency.

Method 2: You can also add the jar dependency to 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>2.6.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Java Code

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideBackground;
import com.spire.presentation.drawing.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;

public class AppplyBgToAllSlides {

    public static void main(String[] args) throws Exception {

        //load a PowerPoint file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("test1.pptx");

        //get the image data
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream("background.jpg"));
        IImageData imageData = presentation.getImages().append(bufferedImage);

        //loop through the slides
        for (int i = 0; i < presentation.getSlides().getCount() ; i++) {

            //apply the image to the specific slide as background
            SlideBackground background = presentation.getSlides().get(i).getSlideBackground();
            background.setType(BackgroundType.CUSTOM);
            background.getFill().setFillType(FillFormatType.PICTURE);
            background.getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
            background.getFill().getPictureFill().getPicture().setEmbedImage(imageData);
        }

        //save the file
        presentation.saveToFile("output/BackgroundImage.pptx", FileFormat.PPTX_2013);
        presentation.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)