Skip to content

Instantly share code, notes, and snippets.

@kzim44
Created February 24, 2013 07:29
Show Gist options
  • Save kzim44/5023021 to your computer and use it in GitHub Desktop.
Save kzim44/5023021 to your computer and use it in GitHub Desktop.
Edit an existing PDF using Python
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(100,100, "Hello world")
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("mypdf.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file("/home/joe/newpdf.pdf", "wb")
output.write(outputStream)
outputStream.close()
@gil-obradors
Copy link

A new version:

from PyPDF2 import PdfFileWriter, PdfFileReader
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

buffer = BytesIO()

# create a new PDF with Reportlab
p = canvas.Canvas(buffer, pagesize=A4)
p.drawString(100, 100, "holaaaaaaaaaaaa")
p.showPage()
p.save()

#move to the beginning of the StringIO buffer
buffer.seek(0)
newPdf = PdfFileReader(buffer)

#######DEBUG NEW PDF created#############
pdf1 = buffer.getvalue()
open('pdf1.pdf', 'wb').write(pdf1)
#########################################
# read your existing PDF
existingPdf = PdfFileReader(open('plantilla.pdf', 'rb'))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existingPdf.getPage(0)
page.mergePage(newPdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open('output.pdf', 'wb')
output.write(outputStream)
outputStream.close()

@PPerz
Copy link

PPerz commented Feb 2, 2021

What if I want to add watermark or some barcode to specify page in pdf, and save it as a one pdf (with e.g. barcode on second page?). How to multiplay pages here?
Thanks

@RealA10N
Copy link

what if I want to replace some text in the pdf?

This is not possible with PDFs. See this answer from Stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment