How to add image to PDF file in Python?
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)
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)
.