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
?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With