How to write at once multiline contents to PDF

2k views Asked by At

I see, that there is a nice library called ReportLab, which makes it possible to do a lot of tricks with PDF files in Python. However, exploring many forum threads, I see everywhere one an the same pattern of writing to PDF line by line:

for line in lines:
    c.drawString(100, 100, line) 

It does not look so well. It would be much better, if we could write to PDF just right away, without having to clone this loop throughout the code. Something, like

c.methodName(10, 10, multiline_contents)
1

There are 1 answers

0
Paritosh On

The draw string methods draw single lines of text on the canvas. The text object interface provides detailed control of text layout parameters not available directly at the canvas level. In addition, it results in smaller PDF that will render faster than many separate calls to the drawString methods.

Something like the following snippet should work for multiline text printing.

def your_function: 
    #canvas is the canvas object instance.
    textobject = canvas.beginText()
    for line in multiline:
        textobject.textLine(line)
    canvas.drawText(textobject)

You can find more information related to the drawing methods here.