0

Right now I'm trying to automate the process of filling out a document using PyPDF2. I've looked across all the documentation and some StackOverflow posts but I essentially see the same sample code which doesn't lead me anywhere. Right now the code just copies the basePDF file and adds text to the new file it just copied. But while trying to add text and save it to the new file, It just clears everything and makes it a blank PDF with "Hello World". How do I keep the original template with the new text without clearing everything?

My code:

from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from shutil import copyfile
copyfile("basePDF.pdf", "newPDF.pdf")

open("newPDF.pdf")

#PyPDF2 Defines
packet = io.BytesIO()

## Read existing PDF
can = canvas.Canvas("newPDF.pdf")
can.setFont("Courier", 16)

can.drawString(10, 100, "Hello world")
can.drawString(0, -10, "Hello world")
can.drawString(10, -100, "Hello world")
can.save()
#Text get's saved but now its a blank PDF with "Hello World"

Thanks in advance!

8
  • There is no method .drawString in PdfFileWriter() class
    – Epsi95
    Commented Feb 1, 2021 at 14:17
  • Yeah just figured that out, now there's no output/changes. Updated the code. Commented Feb 1, 2021 at 14:20
  • what is open("newPDF.pdf")?
    – Epsi95
    Commented Feb 1, 2021 at 14:32
  • That's just there so I can see it pop up in my IDE, without it I can't open it up to view the changes. Commented Feb 1, 2021 at 14:40
  • you want to write on an existing pdf?
    – Epsi95
    Commented Feb 1, 2021 at 14:52

1 Answer 1

4

try this as already mentioned here

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

copyfile("newPDF.pdf", "basePDF.pdf")

packet = io.BytesIO()

# do whatever writing you want to do
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 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(open("basePDF.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 = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.