We often want to dump a lot of data in programming. Tables are a fair way of displaying data and ReportLab supports them. Be warned! The syntax is ugly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python

from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle

doc = SimpleDocTemplate("table.pdf", pagesize=letter)

data = [
    ['Item', 'Cost', 'Quantity'],
    ['Widget', 3.99, 26],
    ['Whatsit', 2.25, 26],
    ['Hooplah', 10.00, 26],
]

parts = []
table = Table(data, [3 * inch, 1.5 * inch, inch])
table_with_style = Table(data, [3 * inch, 1.5 * inch, inch])

table_with_style.setStyle(TableStyle([
    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
    ('FONTSIZE', (0, 0), (-1, -1), 8),
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, 0), 0.25, colors.green),
    ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
]))

parts.append(table)
parts.append(Spacer(1, 0.5 * inch))
parts.append(table_with_style)
doc.build(parts)

The first thing you need to make a Table is some data. Any matrix with a standard number of columns will do. The Table needs two arguments: The data and a sequence of column widths. With that, you can build a Table like any other Flowable. It will look bland, but it will be there.

Tables can be styled to your liking with setStyle and an instance of TableStyle. TableStyles are ugly, syntax-wise. They take one argument, which is a sequence of tailored sequences. For the most part, these tailored sequences are structured as (attribute, start_cell, end_cell, attribute_value). There are a few, like BOX and INNERGRID, that have five values instead of four. The last two are the line width and color. The are more TableStyle attributes than I have used in this example. I would point you to a reference, but I have yet to find one. I will probably make an entire post dedicated to this.

Posted by Tyler Lesmann on January 29, 2009 at 12:53
Tagged as: python reportlab
Post a comment