[Python] How to insert an image in a blank position in a pdf file

Discussão em 'Python' iniciado por Stack, Janeiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    The following script inserts an image into a PDF file using Python (Python AttributeError: 'Page' object has no attribute 'insertImage').

    I would like to identify a blank space in the PDF file that is greater than or equal to the size of the image and insert the image in this location, so that it does not overlap the original content of the PDF file (Example in JAVA: How can I can insert an image or stamp on a pdf where there is free space available like a density scanner ).

    It is a stamp to be filled/signed.

    import fitz

    input_file = "example.pdf"
    output_file = "example-with-sign.pdf"


    # define the position (upper-right corner)
    image_rectangle = fitz.Rect(450,20,550,120)

    # retrieve the first page of the PDF
    file_handle = fitz.open(input_file)
    first_page = file_handle[0]

    img = open("sign.png", "rb").read() # an image file
    img_xref = 0

    first_page.insert_image(image_rectangle,stream=img,xref=img_xref)

    file_handle.save(output_file)

    Continue reading...

Compartilhe esta Página