I am creating report using reportlab. Here is code to insert the text in report
c = canvas.Canvas("reports/abc.pdf", pagesize=A4)
t = c.beginText()
t.setFont('Times-Roman', 14)
t.setTextOrigin(0.3*inch,6.5*inch)
wraped_text = "\n".join(wrap(Desc,100)) # 100 is line width
t.textLines(wraped_text)
c.drawText(t)
This code works with normal string but when some capital letters comes in text its width would increase and it goes out of the page. So, can I set the width of text with respect to width of page rather than depending on the number characters ?
Use reportlab.platypus.Paragraph
instead of drawing to the canvas and you will get the text wrapping for free.
You can compare the Paragraph
to a <div>
in HTML: The Paragraph
will have a width of 100% (of your document) and the height is based on the content.
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
very_long_text = "Your very long text here ..."
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("my_doc.pdf", pagesize=A4)
Story=[]
Story.append(Paragraph(very_long_text, styles["Normal"]))
doc.build(Story)