Python Reportlab PDF - Centering Text on page

jhanifen picture jhanifen · Sep 20, 2010 · Viewed 19.9k times · Source

I am using ReportLab to generate a pdf dynamically with python.

I would like a line of text to be centered on a page. Here is the specific code I currently have, but do not know how to center the text horizontally.

header = p.beginText(190, 740)
header.textOut("Title of Page Here")

# I know i can use TextLine etc in place of textOut

p.drawText(header)

The text displays and I can manually move the left position so the text looks centered, but I need this to be centered programmatically since the text will be dynamic and I don't know how much text there will be.

Answer

Jim Brissom picture Jim Brissom · Sep 21, 2010

The reportlab canvas has a drawCentredString method. And yes, they spell it like that.

We’re British, dammit, and proud of our spelling!

Edit: As for text objects, I'm afraid you don't. You can do something along those lines, though:

from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import defaultPageSize

PAGE_WIDTH  = defaultPageSize[0]
PAGE_HEIGHT = defaultPageSize[1]

text = "foobar foobar foobar"
text_width = stringWidth(text)
y = 1050 # wherever you want your text to appear
pdf_text_object = canvas.beginText((PAGE_WIDTH - text_width) / 2.0, y)
pdf_text_object.textOut(text) # or: pdf_text_object.textLine(text) etc.

You can use other page sizes, obviously.