Search code examples
pythonpdfpdf-generationreportlab

Word wrapping in reportlab


I am using drawCentredString to draw a string in the center of the screen. But if the string is larger than the width of the Canvas, it goes outside the frame. How to handle this such that, it flows downwards?

enter image description here


Solution

  • reportlab.platypus.Paragraph automatically flows text onto a new line. You'll have to use it with a style with center alignment.

    If for some reason you can't use a Paragraph you could use the built in python module textwrap in combination with the function below.

    import textwrap
    
    def draw_wrapped_line(canvas, text, length, x_pos, y_pos, y_offset):
        """
        :param canvas: reportlab canvas
        :param text: the raw text to wrap
        :param length: the max number of characters per line
        :param x_pos: starting x position
        :param y_pos: starting y position
        :param y_offset: the amount of space to leave between wrapped lines
        """
        if len(text) > length:
            wraps = textwrap.wrap(text, length)
            for x in range(len(wraps)):
                canvas.drawCenteredString(x_pos, y_pos, wraps[x])
                y_pos -= y_offset
            y_pos += y_offset  # add back offset after last wrapped line
        else:
            canvas.drawCenteredString(x_pos, y_pos, text)
        return y_pos