Replace Image in Existing PDF File using Python

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.

  1. Load the source PDF with ap.Document(infile).
  2. Open the replacement image as a binary stream.
  3. Replace an image resource by index on a page.
  4. 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.

  1. Load the source PDF.
  2. Create ImagePlacementAbsorber and collect image placements on the page.
  3. Check if any image placements exist on the page.
  4. Replace the selected placement with a new image stream.
  5. 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)