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