I am trying to write some string to a PDF file at some position. I found a way to do this and implemented it like this:
from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = io.StringIO() # create a new PDF with Reportlab 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(file("original.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("destination.pdf", "wb") output.write(outputStream) outputStream.close()
It throws me an error at can.save()
line
The error :
File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfgen/canvas.py", line 1237, in save self._doc.SaveToFile(self._filename, self) File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfbase/pdfdoc.py", line 224, in SaveToFile f.write(data) TypeError: string argument expected, got 'bytes'
Have read up at a lot of places on the internet. Found the same method everywhere. Is it the wrong way to do. Am I missing something?
Advertisement
Answer
Figured out I just had to use BytesIO
instead of StringsIO
.
Also open()
instead of file()
because I’m using Python3.
Here is the working script:
from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = io.BytesIO() # Create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.setFont('Helvetica-Bold', 24) can.drawString(10, 100, "Hello world") can.showPage() 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("original.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()