Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add image to PDF file in Python?

Tags:

python

pdf

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)

like image 640
Nips Avatar asked Nov 07 '12 19:11

Nips


Video Answer


2 Answers

If you're here from Google, PyPDF has been replaced by PyPDF2. The syntax has changed somewhat.

import PyPDF2 as pypdf

with open("original.pdf", "rb") as inFile, open("overlay.pdf", "rb") as overlay:
    original = pypdf.PdfFileReader(inFile)
    background = original.getPage(0)
    foreground = pypdf.PdfFileReader(overlay).getPage(0)

    # merge the first two pages
    background.mergePage(foreground)

    # add all pages to a writer
    writer = pypdf.PdfFileWriter()
    for i in range(original.getNumPages()):
        page = original.getPage(i)
        writer.addPage(page)

    # write everything in the writer to a file
    with open("modified.pdf", "wb") as outFile:
        writer.write(outFile)
like image 102
Quint Avatar answered Oct 11 '22 16:10

Quint


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

page = PdfFileReader(file("document.pdf", "rb")).getPage(0)
overlay = PdfFileReader(file("overlay.pdf", "rb")).getPage(0)
page.mergePage(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).

like image 41
Andrew Buss Avatar answered Oct 11 '22 16:10

Andrew Buss