python wrap text and reportlab
Question:
I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab:
This is how I try:
text = '*long_text_long_text_long_text_long_text*'
text = "n".join(wrap(text, 10))
canvas.drawString(5,227, text)
My pdf was created but where I want to break the lines I can only see black rectangles. You can see the attached picture:
Can you help me? Thank you!
Answers:
drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.
y = 227
for line in wrap(text, 10):
canvas.drawString(5, y, line)
y += 15
An alternative to placing each line individually is using Paragraph:
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A5
from reportlab.platypus import Paragraph
text = "long text<br />long text<br />long text<br />"
text_width=A5[0] / 2
text_height=A5[1] / 2
x = A5[0]/4
y = A5[1]/4
pdf = canvas.Canvas(filename="test.pdf", pagesize=A5)
styles = getSampleStyleSheet()
p = Paragraph(text, styles["Normal"])
p.wrapOn(pdf, text_width, text_height)
p.drawOn(pdf, x, y)
pdf.save()
In addition to supporting manually put line breaks, the Paragraph also supports automatic line breaks.
I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab:
This is how I try:
text = '*long_text_long_text_long_text_long_text*'
text = "n".join(wrap(text, 10))
canvas.drawString(5,227, text)
My pdf was created but where I want to break the lines I can only see black rectangles. You can see the attached picture:
Can you help me? Thank you!
drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.
y = 227
for line in wrap(text, 10):
canvas.drawString(5, y, line)
y += 15
An alternative to placing each line individually is using Paragraph:
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A5
from reportlab.platypus import Paragraph
text = "long text<br />long text<br />long text<br />"
text_width=A5[0] / 2
text_height=A5[1] / 2
x = A5[0]/4
y = A5[1]/4
pdf = canvas.Canvas(filename="test.pdf", pagesize=A5)
styles = getSampleStyleSheet()
p = Paragraph(text, styles["Normal"])
p.wrapOn(pdf, text_width, text_height)
p.drawOn(pdf, x, y)
pdf.save()
In addition to supporting manually put line breaks, the Paragraph also supports automatic line breaks.