Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VALIGN in reportlab TableStyle apparently without effect

So, for a while now I have been struggling with this one. I know there are a lot of similar questions with good answers, and I have tried these answers, but the code I have basically reflects the answers given.

I am writing code to automatically generate matching exercises for worksheets. All this information should be in a table. And the text should all be aligned to the top of the cells.

Here is what I have now:

from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table,         TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm

document = []
doc = SimpleDocTemplate('example.pdf', pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72)
styles = getSampleStyleSheet()

definitions = []
i, a = 1, 65
table = []
for x in range(1, 10):
    line = []
    line.append(Paragraph(str(i), styles['BodyText']))
    line.append(Paragraph('Vocabulary', styles['BodyText']))
    line.append(Paragraph(chr(a), styles['BodyText']))
    line.append(Paragraph('Often a multi-line definition of the vocabulary. But then, sometimes something short and sweet.', styles['BodyText']))
    table.append(line)
    i += 1
    a += 1

t = Table(table, colWidths=(1*cm, 4*cm, 1*cm, None))
t.setStyle(TableStyle([
    ('VALIGN', (1, 1), (-1, -1), 'TOP')
]))

document.append(t)
doc.build(document)

What am I overlooking?

like image 596
toby.in.dresden Avatar asked Mar 11 '23 06:03

toby.in.dresden


1 Answers

The problem is the way you are indexing the TableStyle. The indexing in Reportlab starts at (0, 0) for first row, first column. So in your case (1, 1) only applies the styling to everything below the first row and right of the first column.

The correct way would be to use:

('VALIGN', (0, 0), (-1, -1), 'TOP')

This will apply the styling to all cells in the Table.

like image 54
B8vrede Avatar answered Mar 13 '23 19:03

B8vrede