简体   繁体   中英

Reportlab align text in cells

I try to generate a pdf table with reportlab but I have problems with TableStyle.

Valign and background work but not align and textcolor and I don't understand why.

Here is my code :

response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename.pdf'


doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
doc.pagesize = landscape(A4)
elements = []

data = [
["Equipe", "Partie\n1", "Partie2", "Partie3", "Partie4", "+", "-", "Total", "Parties gagnées", "Place"],
["Equipe", "Partie1", "Partie2", "Partie3", "Partie4", "+", "-", "Total", "Parties gagnées", "Place"],
["Equipe", "Partie1", "Partie2", "Partie3", "Partie4", "+", "-", "Total", "Parties gagnées", "Place"],
["Equipe", "Partie1", "Partie2", "Partie3", "Partie4", "+", "-", "Total", "Parties gagnées", "Place"],
]

#TODO: Get this line right instead of just copying it from the docs
style = TableStyle([
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),
                       ('TEXTCOLOR',(2,2),(2,2),colors.red),
                       ('VALIGN',(0, 0),(-1,-1),'MIDDLE'),                              
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ('BACKGROUND', (2, 3), (2, 3), "#0088cc"),
                        ('BACKGROUND', (0, 1), (-1, 1), lightgrey),
                       ])


#Configure style and word wrap
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
data2 = [[Paragraph(cell, s) for cell in row] for row in data]
colwidths = [3.5*inch, .8*inch, .8*inch, .8*inch, .8*inch, .5*inch, .5*inch, .8*inch, 1*inch, .8*inch]
# Two rows with variable height
# rowheights = [1.4*inch, .2*inch]
t=Table(data2, colwidths)
t.setStyle(style)

#Send the data and build the file
elements.append(t)
doc.build(elements)


return response

The commands 'ALIGN' and 'TEXTCOLOR' don't work, could you help me ?

Thanks.

It is because you have wrapped each Cell into a Paragraph. The Cell is right aligned, but the Paragraph in the cell is left aligned.

If you want a right aligned field, use cell rather than Paragraph(cell, s)

The text will then not wrap though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM