Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add paragraph style reportlab

Tags:

python

pdf

I'm trying to set a paragraph style to report lab, I defined a style here:

def stylesheet():
    styles= {
        'default': ParagraphStyle(
            'default',
            fontName='Arial',
            fontSize=16,
            leading=12,
            leftIndent=0,
            rightIndent=0,
            firstLineIndent=0,
            alignment=TA_LEFT,
            spaceBefore=0,
            spaceAfter=0,
            bulletFontName='Arial',
            bulletFontSize=10,
            bulletIndent=0,
            textColor= black,
            backColor=None,
            wordWrap=None,
            borderWidth= 0,
            borderPadding= 0,
            borderColor= None,
            borderRadius= None,
            allowWidows= 1,
            allowOrphans= 0,
            textTransform=None,  # 'uppercase' | 'lowercase' | None
            endDots=None,         
            splitLongWords=1,
        ),
    }

Then I print it like that

   pdf = PDFDocument(carte)
    pdf.init_report()
    pdf.p(str(row))
    pdf.generate()

Which gives an unformatted output

When I try

pdf = PDFDocument(carte)
pdf.init_report()
pdf.p(str(row), default)
pdf.generate()

To apply the default style to my text, it gives me 'NameError: name 'styles' is not defined'

Any clue?

like image 522
Effedepay Avatar asked Dec 25 '22 03:12

Effedepay


1 Answers

I've been struggling with this for a few hours, as of today the solution provided didn't work for me. I found another on programcreek that almost did. After a little retouch this one did the trick:

#First you need to instantiate 'getSampleStyleSheet()'
from reportlab.lib.styles import (ParagraphStyle, getSampleStyleSheet)
style = getSampleStyleSheet()
yourStyle = ParagraphStyle('yourtitle',
                           fontName="Helvetica-Bold",
                           fontSize=16,
                           parent=style['Heading2'],
                           alignment=1,
                           spaceAfter=14)

To use it just call yourStyle like this:

Story.append(Paragraph("Whatever printed with yourStyle", yourStyle))

Alignment must be given with a number as indicated in the docs:

There are four possible values of alignment, defined as constants in the module reportlab.lib.enums. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.

I'm posting the answer because I couldn't find a precise answer anywhere in the hope that it might help other people.

like image 95
Arturo Mendes Avatar answered Jan 10 '23 05:01

Arturo Mendes