0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python の ReportLab で PDF に表を描画

Posted at

やりたいこと

PDF ライブラリとして ReportLab を使用し、以下のような表を描画する。

  • 日本語文字列を表示する
  • 表が1ページにおさまらない場合に改ページする
  • 表のタイトルを表示する
  • 表の高さを可変にしてテキストがおさまるようにする

ReportLab

日本語文字列の表示

font_name に任意のフォント名を指定し、font_path を指定してフォントを登録する。
style で fontName に font_name を指定するとそのフォントを使用することができる。

pdfmetrics.registerFont(TTFont(font_name, font_path, subfontIndex=0))

表の作成

LongTable を使うと、1ページに表がおさまらない場合に、改ページして表を表示することができる。

table = LongTable(
    table_contents,     # 表に表示する文字列のデータ
    style=table_style,  # スタイル
    colWidths=30*mm,    # 幅 30mm
    rowHeights=20*mm,   # 高さ 20mm
    repeatRows=1,       # 改ページした際にヘッダとする先頭行数
)

表のタイトル

Paragraph で表のタイトルを表示し、Spacer で表との間隔を調整する。

styles = getSampleStyleSheet()
title_style = ParagraphStyle(
    'titleStyle',
    parent=styles['Heading2'],
    fontName=font_name,
    alignment=1,  # 1:center
)
title = Paragraph('表1. 商品一覧', title_style)

Spacer(1, 12) # 幅1 pt、高さ 12pt

テーブルの高さを可変

LongTable() のパラメータに rowHeight を指定しなければ高さが可変になる

table = LongTable(
    table_contents,
    style=table_style,
    colWidths=30*mm,    # 幅 30mm
    # rowHeights=20*mm, # 高さを指定しないと可変になる
    repeatRows=1,
)

プログラム例

import os
import sys
import platform
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, LongTable, Paragraph, Spacer

# 日本語フォントの設定
# Windows: MS Gothic
# Mac: Hiragino
# Linux: VL Gothic
def set_japanese_font(font_name):
    os_name = platform.system()

    if os_name == "Windows":
        font_path = os.path.join(os.environ['SYSTEMROOT'], 'Fonts', 'msgothic.ttc')
        pdfmetrics.registerFont(TTFont(font_name, font_path, subfontIndex=0))
    elif os_name == "Darwin":
        font_path = '/System/Library/Fonts/Hiragino Sans W3.ttc'
        pdfmetrics.registerFont(TTFont(font_name, font_path, subfontIndex=0))
    else:
        font_path = '/usr/share/fonts/vl-gothic-fonts/VL-Gothic-Regular.ttf'
        if not os.path.exists(font_path):
            raise Exception
        pdfmetrics.registerFont(TTFont(font_name, font_path))

def main():
    # 日本語フォント
    font_name = "SystemFont"
    font = set_japanese_font(font_name)

    doc = SimpleDocTemplate(
        filename="test1.pdf",
        pagesize=landscape(A4),
    )

    elements = []

    # タイトル
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'titleStyle',
        parent=styles['Heading2'],
        fontName=font_name,
        alignment=1,  # 1:center
    )
    title = Paragraph('表1. 商品一覧', title_style)
    elements.append(title)

    # 空白
    elements.append(Spacer(1, 12)) # 幅1 pt、高さ 12pt

    # テーブル
    # ヘッダ
    table_contents = [
        ["No.", "code", "name", "price", "text"],
    ]

    # 本体
    for i in range(0, 10):
        table_contents.append([
            f"{i+1}",
            f"code_{i+1}",
            f"name_{i+1}",
            f"{i * 20,}",
            '\n'.join("*" * (i+1)),
        ])

    table_style = [
        # セルの対象の範囲は (col1, row1) - (col2, row2)
        # 表全体に 0.5 ポイントのグリッド線を描画
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        # 表全体を囲む枠を 1.0 ポイントで描画
        ('BOX', (0, 0), (-1, -1), 1.0, colors.black),
        # ヘッダの背景をグレー
        ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
        # align を設定
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ]

    table = LongTable(
        table_contents,
        style=table_style,
        colWidths=30*mm,
        # rowHeights=20*mm, # 可変にする場合には指定しない
        repeatRows=1,
    )

    elements.append(table)
    doc.build(elements)

    return 0


if __name__ == '__main__':
    exit(main())

実行結果

上記のプログラムを linux で実行した。

  • 1ページ目
    table_page1.png
  • 2ページ目
    table_page2.png

Linux での VLゴシック / VL Pゴシックのインストール

sudo yum install vlgothic-fonts vlgothic-p-fonts
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?