Pedroski
Pedroski

Reputation: 497

Writing a string to pdf with PyPDF2

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:
        pdf_writer.write(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'

Upvotes: 8

Views: 24946

Answers (3)

Von
Von

Reputation: 4525

One way (and the only way I see) to do this with PyPDF2 is with annotations.

writer = PyPDF2.PdfWriter()
# Need to specify page size since there is no prior page to
# draw size from.
writer.add_blank_page(800.0, 800.0)

annotation = PyPDF2.generic.AnnotationBuilder.free_text(
    "Hello World\nThis is the second line!",
    rect=(50, 550, 200, 650),
    font="Arial",
    bold=True,
    italic=True,
    font_size="20pt",
    font_color="00ff00",
    border_color="0000ff",
    background_color="cdcdcd",
)
writer.add_annotation(page_number=0, annotation=annotation)

with open(outputfilename, "wb") as fp:
    writer.write(fp)

Upvotes: 1

gbajson
gbajson

Reputation: 1770

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')

Upvotes: 0

Fabian
Fabian

Reputation: 1150

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")
pdf.output("test.pdf")

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.

Upvotes: 5

Related Questions