简体   繁体   中英

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?

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM