Java/ Replace Images in PDF

Java/ Replace Images in PDF

·

1 min read

As we all know, PDF is a kind of document format that hard to edit. But when receiving a PDF document from others, you may need to make minor modifications to it, such as replacing the image in the document with a new image. This article will demonstrate how to accomplish this task using Free Spire.PDF for Java.

Import Jar Dependency (2 Methods)

Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml file.

<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.pdf.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Sample Code

Free Spire.PDF for Java offers the PdfPageBase.replaceImage() method to replace the existing image with a new image in a PDF document. The complete sample code is shown as below.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

import java.io.IOException;

public class ReplaceImage {
    public static void main(String[] args) throws IOException {
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Olympics.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\Olympics.jpg");

        //Replace the first image in the first page with the loaded image
        page.replaceImage(0, image);

        //Save the file
        pdf.saveToFile("ReplaceImage.pdf");
    }
}

replaceImage.jpg