Search code examples
pythonreportlab

ReportLab Python horizontal centre alignment


I'm trying to horizontally centre a simple text on a custom size PDF using reportlab. My code is below. I've tried using doc.drawCentredString but this then chops the beginning of the text off. As it is right now the text aligns at the bottom left corner. But as the text will be dynamic I can't really set a fixed horizontol position because it won't always end up centred.

My code is:

from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas

doc = Canvas('document.pdf')
doc.setPageSize((72 * mm, 160 * mm))

doc.setFillColorRGB(1,0,0)
doc.setFont("Helvetica", 14)
doc.drawString(0,0,"Hello World")

doc.showPage()
doc.save()

Can anyone tell me how I can make the text centred of the document please?


Solution

  • Canvas.drawCentredString() places center of string into coordinate you specify, it should be center of the page not 0.

    from reportlab.lib.units import mm
    from reportlab.pdfgen.canvas import Canvas
    
    doc = Canvas('document.pdf')
    doc.setPageSize((72 * mm, 160 * mm))
    
    doc.setFillColorRGB(1,0,0)
    doc.setFont("Helvetica", 14)
    
    x = doc._pagesize[0] / 2
    
    doc.drawCentredString(x, 0, "Hello World")
    
    doc.showPage()
    doc.save()