【问题标题】:how to separate list to different tables & print the tables to individual pages pdf in reportlab?如何将列表分隔到不同的表格并将表格打印到reportlab中的各个页面pdf?
【发布时间】:2021-08-02 11:02:31
【问题描述】:

我有一个列表列表

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)]
        ]

我想为每个列表创建一个不同的表:1 个列表到每页 1 个表中,就像这样:

如何将列表分成不同的表格?并使用reportlab将它们放在不同的页面上?假设列表的数量并不总是 2,因为数据来自数据库?

【问题讨论】:

  • 您的示例表明 data1 是指一个列表列表,其中每个元素都是一个 6 项元组。您可以使用“for innerlist in data1”遍历列表,然后从 innerlist 中创建 PDF

标签: python list pdf reportlab


【解决方案1】:

只需使用for-loop 单独处理每个列表

for data in data1:
    table = Table(data)

最少的工作代码

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)

【讨论】:

  • 我明白了!我错过了 PageBreak(),谢谢!
  • 如果您要显示有问题的代码,那么您将得到它,而无需所有这些示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2018-11-15
相关资源
最近更新 更多