I have been trying to create a pdf using PyPDF2 and Reprortlab. I need to draw a flowable paragraph with huge chunk of text. The problem is the size of the paragraph may vary. I want to keep the top-left corner (start of the paragraph) of the paragraph fixed for all the pages. The problem is when I draw the paragraph at a fixed location (x,y on Canvas) the bottom left corner stays at this location (x,y). I guess this is the deafult behaviour of ReportLab. Is there a tweak or work around to start the paragraph from the top left instead of bottom left so that the paragraphs start from the same location irrespective of the size of the paragraph?
Asked
Active
Viewed 4,467 times
2 Answers
8
When using the wrap function of a paragraph, it will return the total height of the wrapped text. This can be used in combination with the location desired for the text to create the appearance of drawing the text from 0,0 being top-left instead of bottom-left.
def draw_paragraph(canvas, msg, x, y, max_width, max_height):
message_style = ParagraphStyle('Normal')
message = msg.replace('\n', '<br />')
message = Paragraph(message, style=message_style)
w, h = message.wrap(max_width, max_height)
message.drawOn(canvas, x, y - h)

daredoes
- 104
- 1
- 2
1
#can canvas
#openbd is just font opensas it is custom font
# you can remove fontname parameter
def draw_paragraphcontent(self, can, msg, x, y, max_width, max_height, color, fontsize, text_align=TA_CENTER,
fontname='openbd'):
message_style = ParagraphStyle('Normal', fontName=fontname, textColor=color, fontSize=fontsize,
alignment=text_align)
message = msg.replace('\n', '<br />')
message = Paragraph(message, style=message_style)
w, h = message.wrap(max_width, max_height)
message.drawOn(can, x, y - h)
pass
sample:

lava
- 6,020
- 2
- 31
- 28