Replace Image in Existing PDF File using Python
Contents
[
Hide
]
Replace an Image in PDF
Use this page when you need to update logos, diagrams, or other embedded graphics in a PDF without rebuilding the document layout.
- Load the source PDF with
ap.Document(infile). - Open the replacement image as a binary stream.
- Replace an image resource by index on a page.
- Save the updated PDF.
import aspose.pdf as ap
from io import FileIO
def replace_image(infile, image_file, outfile):
document = ap.Document(infile)
with FileIO(image_file, "rb") as image_stream:
document.pages[1].resources.images.replace(1, image_stream)
document.save(outfile)
Replace a Specific Image
This example replaces a specific image placement found by ImagePlacementAbsorber.
- Load the source PDF.
- Create
ImagePlacementAbsorberand collect image placements on the page. - Check if any image placements exist on the page.
- Replace the selected placement with a new image stream.
- Save the updated PDF.
import aspose.pdf as ap
from io import FileIO
def replace_image_with_absorber(infile, image_file, outfile):
document = ap.Document(infile)
absorber = ap.ImagePlacementAbsorber()
document.pages[1].accept(absorber)
if len(absorber.image_placements) > 0:
image_placement = absorber.image_placements[1]
with FileIO(image_file, "rb") as image_stream:
image_placement.replace(image_stream)
document.save(outfile)