Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write multiple lines of text in a flow with reportlab

This works to write a text in a PDF file with reportlab:

from reportlab.pdfgen import canvas
from reportlab.lib.units import cm

c = canvas.Canvas("test.pdf")
c.drawString(1 * cm, 29.7 * cm - 1 * cm, "Hello")
c.save()

but when dealing with multiple lines of text, it's unpleasant to have to handle the x, y coordinate of each new line:

text = "Hello\nThis is a multiline text\nHere we have to handle line height manually\nAnd check that every line uses not more than pagewidth"
c = canvas.Canvas("test.pdf")

for i, line in enumerate(text.splitlines()):
    c.drawString(1 * cm, 29.7 * cm - 1 * cm - i * cm, line)

c.save()

Is there a more clever way to do this with reportlab?

like image 839
Basj Avatar asked May 25 '18 15:05

Basj


1 Answers

One option is to use the Flowables that reportlab provides, one type of flowable element is a Paragraph. Paragraphs support <br> as line breaks.

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm

my_text = "Hello\nThis is a multiline text\nHere we do not have to handle the positioning of each line manually"

doc = SimpleDocTemplate("example_flowable.pdf",pagesize=A4,
                        rightMargin=2*cm,leftMargin=2*cm,
                        topMargin=2*cm,bottomMargin=2*cm)

doc.build([Paragraph(my_text.replace("\n", "<br />"), getSampleStyleSheet()['Normal']),])

A second option is to use drawText with a TextObject:

c = canvas.Canvas("test.pdf")
textobject = c.beginText(2*cm, 29.7 * cm - 2 * cm)
for line in my_text.splitlines(False):
    textobject.textLine(line.rstrip())
c.drawText(textobject)
c.save()
like image 125
Joran Beasley Avatar answered Sep 28 '22 17:09

Joran Beasley