3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonAdvent Calendar 2022

Day 8

ReportLabで長い表を作るとき、改ページ後にもテーブルヘッダーを表示する

Last updated at Posted at 2022-12-07

ReportLabでPDFを作るシリーズ第2弾

DocTemplateとLongTableを使おう

SimpleDocTemplateの使い方

doc = SimpleDocTemplate(filename=filename)
flowables = [
    # Flowableオブジェクトのリスト
]
doc.build(flowables)

もっと複雑なレイアウトの例は第1弾の お前らのReportLabの使い方は間違っているを参照

LongTableの使い方

table = LongTable(table_contents, repeatRows=1)

repeatRowsを指定することで改ページ時に繰り返す行を指定する

TableStyleをセットして、罫線や寄せなどを指定できる。

サンプルソース

from reportlab.lib import colors
from reportlab.platypus import (LongTable, Paragraph, SimpleDocTemplate,
                                TableStyle)


def main() -> None:
    filename = "/tmp/temp.pdf"
    doc = SimpleDocTemplate(filename=filename)
    table_style = TableStyle(
        [
            ("ALIGN", (0, 0), (-1, 0), "CENTER"),  # header
            ("GRID", (0, 0), (-1, 0), 2, colors.red),  # header
            ("GRID", (0, 0), (-1, -1), 1, colors.black),  # body
        ]
    )
    header1 = Paragraph("<font color='blue'>header1</font>")
    table_contents = [
        [header1, "header2", "header3"],
    ]
    for i in range(1, 51):
        table_contents.append([f"row {i}", f"{i+100}", f"{i+200}"])
    table = LongTable(table_contents, repeatRows=1)
    table.setStyle(table_style)

    flowables = [table]

    doc.build(flowables)


if __name__ == "__main__":
    main()

出力結果

reoprtlab_test.png

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?