How to add image to PDF file in Python?

Question:

I have a PDF document but I must put my own image on it. It’s an official document and I must apply an image with the text “example” to the whole page.

Is there any way to solve this problem in python?

(text in the document is curves)

Asked By: Nips

||

Answers:

Look into pypdf. You might use something like the following code to apply an overlay:

page = PdfReader("document.pdf").pages[0]
overlay = PdfReader("overlay.pdf").pages[0]
page.merge_page(overlay)

Put any overlay you want, including "Example", into overlay.pdf.
Personally, I prefer PDFTK, which, while not strictly Python, can be invoked from a script with os.system(command).

Answered By: Andrew Buss

If you’re here from Google, pypdf > 3.0.0 is the latest project. PyPDF2 / PyPDF3 / PyPDF4 are no longer maintained as you can see in their latest release date. The syntax has changed somewhat.

import pypdf

# overlay.pdf contains the image
with open("original.pdf", "rb") as inFile, open("overlay.pdf", "rb") as overlay:
    original = pypdf.PdfReader(inFile)
    background = original.pages[0]
    foreground = pypdf.PdfReader(overlay).pages[0]
    
    # merge the first two pages
    background.merge_page(foreground)
    
    # add all pages to a writer
    writer = pypdf.PdfWriter()
    for page in original.pages:
        writer.add_page(page)
    
    # write everything in the writer to a file
    with open("modified.pdf", "wb") as outFile:
        writer.write(outFile)
Answered By: Quint
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.