2

I am trying to write text on a PDF file but if the line is bigger than the page size it overflows and doesn't automatically go to the next line. How do I provide a range when the line overflows and automatically break the text to the next line?

Note: The text is automatically generated and may always not overflow.

Current Output: enter image description here

What I want: enter image description here

Code:

can = canvas.Canvas(packet, pagesize=A4, bottomup=0)
can.setFont('RobotoBold', 11)
can.drawString(40, 658, 'In Word:')
can.setFont('Roboto', 11)
can.drawString(84, 658, final_string)
Mehadi
  • 85
  • 8
  • `canvas.Canvas.drawString` is useful sometimes, but don't over-rely on it. You need to use a `flowable`. RTFM - page 65 is a good place to start. https://www.reportlab.com/docs/reportlab-userguide.pdf – GordonAitchJay Feb 14 '22 at 06:35

1 Answers1

0

You can break final_string into chunks by using list comprehension as follows.

n = 80 # or whatever length you find suitable.
finals_string_chunks = [final_string[i:i+n] for i in range(0, len(final_string), n)]

And then call can.drawString() within a for-each loop for each string in the list finals_string_chunks.

You might have to do some math for updating appropriate x, y coordinates on your drawString method as well.

Rajdeep Biswas
  • 187
  • 2
  • 11
  • Thanks for the comment! However, in your approach, there is a possibility of breaking the words in between as the loop is breaking based on length. For example a word can be broken like Hund red – Mehadi Feb 14 '22 at 08:50