Writing a string to pdf with PyPDF2

Asked by At

I will read 130+ excel files in as lines of strings in Python. I want to write each line to a pdf. The whole excel file is just 1 A5 landscape sheet. I can batch print pdfs in a bash shell easily.

I import PyPDF2

I can create a pdf or a series pdf files with:

with open(path + fileName, 'wb') as out:

but I'm too dumb to see how to write a string to this pdf. If I try to write a string variable, I just get errors. If I convert the string to bytes, I just get errors.

How do I get string into my pdf?

string = 'any old string'

2 Answers

Fabian On

I know you asked for PyPDF2 but more simple approach with FPDF:

# https://pyfpdf.readthedocs.io/en/latest/
import fpdf #pip3 intall fpdf

pdf = fpdf.FPDF(format='letter') #pdf format
pdf.add_page() #create new page
pdf.set_font("Arial", size=12) # font and textsize
pdf.cell(200, 10, txt="your text", ln=1, align="L")
pdf.cell(200, 10, txt="your text", ln=2, align="L")
pdf.cell(200, 10, txt="your text", ln=3, align="L")

As you mentioned you dont understand, PyPDF doc so well so i think FPDF is a good start.

PyPDF2 is more suited for reading and merging pdf files.

If you realy like to use PyPDF2 you could achieve text with canvas.

gbajson On

PyPDF2 is very good choice when you need to change existing PDFs, but it requires knowledge of pdf format when you need to create PDF from scratch.

You might consider using a different library for this task i.e. pdfkit (https://github.com/JazzCore/python-pdfkit), sample program:

import pdfkit

pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')