Skip to content

Instantly share code, notes, and snippets.

@haleyrc
Created April 16, 2019 21:01
Show Gist options
  • Save haleyrc/5c5e6e96be7b3ba8c8c4b918215f7947 to your computer and use it in GitHub Desktop.
Save haleyrc/5c5e6e96be7b3ba8c8c4b918215f7947 to your computer and use it in GitHub Desktop.
Demonstration of merging text onto existing pdf
from PyPDF2 import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
# Create a new PDF with the text to overlay
packet = StringIO.StringIO()
can = canvas.Canvas(packet)
can.drawString(200, 100, "Goodbye World")
can.save()
# Move to the beginning of the buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# Read the existing pdf
existing_pdf = PdfFileReader(file("hello.pdf", "rb"))
output = PdfFileWriter()
# Merge the contents of the two pages
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# Write out the new file
outputStream = file("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()
from reportlab.pdfgen import canvas
def hello(c):
c.drawString(100,100,"Hello World")
c = canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment