News Category

Replace image with new image in PDF in Java

2019-04-01 08:25:21 Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to replace an existing image with a new image in a PDF file using Spire.PDF for Java.

Below is the screenshot of the input PDF file we used for demonstration:

Replace image with new image in PDF in Java

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("Input.pdf");

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

        //Load an image
        PdfImage image = PdfImage.fromFile("Image.png");

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

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

Output:

Replace image with new image in PDF in Java

Additional Info

  • tutorial_title:
Last modified on Thursday, 02 September 2021 06:31