views:

44

answers:

1

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.

+2  A: 

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.

Jim Brissom
Thanks Jim,I used p.drawCentredString(4.25*inch, 500, 'some text')that works great, but how do I use drawCentredString with .textOut or .textLine? p.drawCentredString(center, 500, header);
jhanifen
See my edit for an answer to that.
Jim Brissom
Thanks, that should work, not as pretty but does the job!
jhanifen