Eins
Eins

Reputation: 71

How to align text to center in reportlab python?

I am generating a pdf using reportlab and I want my title to be in center. But how do achieve it, unable to find a soltuion.

Here is my code:

def add_text(text, style="Normal", fontsize=12):
    Story.append(Spacer(1, 12))
    ptext = "<font size={}>{}</font>".format(fontsize, text)
    Story.append(Paragraph(ptext, styles[style]))
    Story.append(Spacer(1, 12))

add_text("Title", style="Heading1", fontsize=24)

Upvotes: 6

Views: 12068

Answers (1)

Jaco
Jaco

Reputation: 1694

I would create my own text style and refer to this, in your case

def add_text(text, style="Normal", fontsize=12):

to

def add_text(text, style="Normal_CENTER", fontsize=12):

Below is how you create your own style:

from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT
from reportlab.lib import colors

styles = getSampleStyleSheet()

styles.add(ParagraphStyle(name='Normal_CENTER',
                          parent=styles['Normal'],
                          fontName='Helvetica',
                          wordWrap='LTR',
                          alignment=TA_CENTER,
                          fontSize=12,
                          leading=13,
                          textColor=colors.black,
                          borderPadding=0,
                          leftIndent=0,
                          rightIndent=0,
                          spaceAfter=0,
                          spaceBefore=0,
                          splitLongWords=True,
                          spaceShrinkage=0.05,
                          ))
styles.add(ParagraphStyle(name='New Style',
                          alignment=TA_LEFT,
                          fontName='Helvetica',
                          fontSize=7,
                          textColor=colors.darkgray,
                          leading=8,
                          textTransform='uppercase',
                          wordWrap='LTR',
                          splitLongWords=True,
                          spaceShrinkage=0.05,
                          ))

Upvotes: 4

Related Questions