Replace Image in Existing PDF File using Java
Contents
[
Hide
]
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
- Open the source PDF Document.
- Access the image resources on the target Page.
- Replace the target image resource with the new image file.
- 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
- Open the source PDF Document.
- Create an ImagePlacementAbsorber and visit the target Page.
- Get the target ImagePlacement and replace it with the new image stream.
- 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());
}
}