Search code examples
pythonreportlab

Python String Wrap


I want to wrap the string at 30,700 in this script. What is the best way of doing this, I have tried using textWrap but it does not seem to work. This is my code:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

canvas = canvas.Canvas("Forensic Report.pdf", pagesize=letter)
canvas.setLineWidth(.3)
canvas.setFont('Helvetica', 12)

canvas.drawString(30,750,'LYIT MOBILE FORENSICS DIVISION')
canvas.drawString(500,750,"Date: 12/02/2018")
canvas.line(500,747,595,747)

canvas.drawString(500,725,'Case Number:')
canvas.drawString(580,725,"10")
canvas.line(500,723,595,723)


canvas.drawString(30, 700, 'This forensic report has been compiled by the forensic examiner in conclusion to the investigation into the RTA case which occured on 23/01/2018')


canvas.save()
print("Forensic Report Generated")

Solution

  • Perhaps you want to use the drawText? Doing so, your code will be

    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    
    canvas = canvas.Canvas("Forensic Report.pdf", pagesize=letter)
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'LYIT MOBILE FORENSICS DIVISION')
    canvas.drawString(500,750,"Date: 12/02/2018")
    canvas.line(500,747,595,747)
    
    canvas.drawString(500,725,'Case Number:')
    canvas.drawString(580,725,"10")
    canvas.line(500,723,595,723)
    
    line1 = 'This forensic report has been compiled by the forensic'
    line2 = 'examiner in conclusion to the investigation into the RTA'
    line3 = 'case which occured on 23/01/2018'
    textobject = canvas.beginText(30, 700)
    lines = [line1, line2, line3]
    for line in lines:
        textobject.textLine(line)
    
    canvas.drawText(textobject)
    canvas.save()
    

    This is also the solution suggested here. Unfortunately, I do not see it as a valid solution for automatic text wrapping in new lines, i.e. you should manage how to split the string yourself.