Replace Image in Existing PDF File using Java

Use either the page image collection or placement-based search depending on how precisely you need to target the image.

Replace an image by resource index

  1. Open the source PDF Document.
  2. Access the image resources on the target Page.
  3. Replace the target image resource with the new image file.
  4. Save the updated PDF Document.
public static void replaceImage(Path inputFile, Path imageFile, Path outputFile) throws Exception {
    try (Document document = new Document(inputFile.toString());
         InputStream imageStream = Files.newInputStream(imageFile)) {
        document.getPages().get_Item(1).getResources().getImages().replace(1, imageStream);
        document.save(outputFile.toString());
    }
}

Replace an image using ImagePlacementAbsorber

  1. Open the source PDF Document.
  2. Create an ImagePlacementAbsorber and visit the target Page.
  3. Get the target ImagePlacement and replace it with the new image stream.
  4. Save the updated PDF Document.
public static void replaceImageWithAbsorber(Path inputFile, Path imageFile, Path outputFile) throws Exception {
    try (Document document = new Document(inputFile.toString())) {
        ImagePlacementAbsorber absorber = new ImagePlacementAbsorber();
        document.getPages().get_Item(1).accept(absorber);

        if (absorber.getImagePlacements().size() > 0) {
            ImagePlacement imagePlacement = absorber.getImagePlacements().get_Item(1);
            try (InputStream imageStream = Files.newInputStream(imageFile)) {
                imagePlacement.replace(imageStream);
            }
        }

        document.save(outputFile.toString());
    }
}