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:
JavaScript
x
26
26
1
from PyPDF2 import PdfFileWriter, PdfFileReader
2
import io
3
from reportlab.pdfgen import canvas
4
from reportlab.lib.pagesizes import letter
5
6
packet = io.StringIO()
7
# create a new PDF with Reportlab
8
can = canvas.Canvas(packet, pagesize=letter)
9
can.drawString(10, 100, "Hello world")
10
can.save()
11
12
#move to the beginning of the StringIO buffer
13
packet.seek(0)
14
new_pdf = PdfFileReader(packet)
15
# read your existing PDF
16
existing_pdf = PdfFileReader(file("original.pdf", "rb"))
17
output = PdfFileWriter()
18
# add the "watermark" (which is the new pdf) on the existing page
19
page = existing_pdf.getPage(0)
20
page.mergePage(new_pdf.getPage(0))
21
output.addPage(page)
22
# finally, write "output" to a real file
23
outputStream = file("destination.pdf", "wb")
24
output.write(outputStream)
25
outputStream.close()
26
It throws me an error at can.save()
line
The error :
JavaScript
1
6
1
File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfgen/canvas.py", line 1237, in save
2
self._doc.SaveToFile(self._filename, self)
3
File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfbase/pdfdoc.py", line 224, in SaveToFile
4
f.write(data)
5
TypeError: string argument expected, got 'bytes'
6
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:
JavaScript
1
28
28
1
from PyPDF2 import PdfFileWriter, PdfFileReader
2
import io
3
from reportlab.pdfgen import canvas
4
from reportlab.lib.pagesizes import letter
5
6
packet = io.BytesIO()
7
# Create a new PDF with Reportlab
8
can = canvas.Canvas(packet, pagesize=letter)
9
can.setFont('Helvetica-Bold', 24)
10
can.drawString(10, 100, "Hello world")
11
can.showPage()
12
can.save()
13
14
# Move to the beginning of the StringIO buffer
15
packet.seek(0)
16
new_pdf = PdfFileReader(packet)
17
# Read your existing PDF
18
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
19
output = PdfFileWriter()
20
# Add the "watermark" (which is the new pdf) on the existing page
21
page = existing_pdf.getPage(0)
22
page.mergePage(new_pdf.getPage(0))
23
output.addPage(page)
24
# Finally, write "output" to a real file
25
outputStream = open("destination.pdf", "wb")
26
output.write(outputStream)
27
outputStream.close()
28