Replace Image in Existing PDF File using Python
Contents
[
Hide
]
Replace an Image in PDF
How to replace an existing image on a PDF page with a new image? Implement this using Aspose.PDF for Python via .NET.
- Import necessary modules (aspose.pdf, os.path, FileIO).
- Define paths for:
- Input PDF (infile)
- New image file (image_file)
- Output PDF (outfile)
- Load the PDF document using ‘apdf.Document(path_infile)’.
- Open the new image file in binary read mode.
- Replace the first image on the first page:
- ‘document.pages[1].resources.images.replace(1, image_stream)’
- Save the updated PDF to ‘path_outfile’.
import aspose.pdf as apdf
from io import FileIO
from os import path
path_infile = path.join(self.data_dir, infile)
path_image_file = path.join(self.data_dir, image_file)
path_outfile = path.join(self.data_dir, outfile)
document = apdf.Document(path_infile)
with FileIO(path_image_file, "rb") as image_stream:
document.pages[1].resources.images.replace(1, image_stream)
document.save(path_outfile)
Replace specific Image
This example demonstrates how to replace a specific image on a PDF page by locating it via image placement detection.
- Load the PDF using ‘apdf.Document()’.
- Create an ‘ImagePlacementAbsorber’ to collect all image placements on the page.
- Accept the absorber on the first page (‘document.pages[1].accept(absorber)’).
- Check if any image placements exist on the page.
- Select the first image placement (absorber.image_placements[1]) and replace it.
- Save the modified PDF to ‘path_outfile’.
import aspose.pdf as apdf
from io import FileIO
from os import path
path_infile = path.join(self.data_dir, infile)
path_image_file = path.join(self.data_dir, image_file)
path_outfile = path.join(self.data_dir, outfile)
document = apdf.Document(path_infile)
# Create ImagePlacementAbsorber to find image placements
absorber = apdf.ImagePlacementAbsorber()
# Accept the absorber for the first page
document.pages[1].accept(absorber)
# Replace the first image placement found
if len(absorber.image_placements) > 0:
image_placement = absorber.image_placements[1]
with FileIO(path_image_file, "rb") as image_stream:
image_placement.replace(image_stream)
document.save(path_outfile)