Skip to content
Advertisement

how to separate list to different tables & print the tables to individual pages pdf in reportlab?

I have a list of lists

data1 = [[('Glass',1.0,'Hardware',900,900,398826),
          ('Mirror',5.0,'Hardware',18000,300,398826),
          ('Plastic',3.0,'Hardware',200,15,398826)],
         [('Metal',1.0,'Hardware',900,900,358947),
          ('Wood',5.0,'Hardware',18000,300,358947)]
        ]

and i want to create a different table per list: 1 list into 1 table per page, just like this: enter image description here

how do i separate the list into different tables? and have them on different pages using reportlab? assuming that the number of the lists is not always 2 because the data came from a database?

Advertisement

Answer

Simply use for-loop to work with every list separatelly

for data in data1:
    table = Table(data)

Minimal working code

from reportlab.lib import colors
#from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, PageBreak

all_data = [
    [
        ('Glass',1.0,'Hardware',900,900,398826),
        ('Mirror',5.0,'Hardware',18000,300,398826),
        ('Plastic',3.0,'Hardware',200,15,398826)
    ],
    [
        ('Metal',1.0,'Hardware',900,900,358947),
        ('Wood',5.0,'Hardware',18000,300,358947)
    ]
]

doc = SimpleDocTemplate("output.pdf")

table_style = TableStyle([
        #('BACKGROUND', (1,1), (-2,-2), colors.green),
        #('TEXTCOLOR', (0,0), (1,-1), colors.red),
        ('BOX', (0,0), (-1,-1), 0.45, colors.black),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.blue),
    ])

elements = []

for data in all_data:
    table = Table(data, style=table_style)
    #table.setStyle(table_style)
    elements.append(table)
    elements.append(PageBreak())

# write the document to disk
doc.build(elements)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement