Columns measured from their cells

One parts list twice: four columns sharing the width equally, then the reference, the quantity and the price each as wide as their own widest cell and the description given everything they leave.

Python write_measured_columns.py 237 lines
  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
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""Draws one parts list twice: columns of equal width, then columns measured
from what they hold.

The Python twin of the `write_measured_columns` example in Rust. The rows are
the same in both tables. In the first the four columns share the width equally,
so the references and the figures sit in far more room than they need and the
descriptions wrap for want of it. In the second the reference, the quantity and
the price are each as wide as their own widest cell, and the description is
given everything they leave.

What the page reads is held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. The references, the quantities and the prices are not language:
they are the same figures whoever reads the list.

Usage: python examples/write_measured_columns.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_measured_columns.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margins, the top of the first table, and the room between the two.
MARGIN = 56.0
TOP = 740.0
GAP = 64.0
PAGE_WIDTH = 595.276
TABLE_WIDTH = PAGE_WIDTH - 2 * MARGIN


@dataclass(frozen=True)
class Part:
    """One line of the parts list, save what it is called."""

    reference: str
    quantity: str
    price: str


# The figures the list holds. They are short and all of a length, whatever language the
# list is read in; what each part is called is in `Words`.
PARTS = [
    Part("HQF-1042", "2", "48.00"),
    Part("HQF-1043", "2", "26.50"),
    Part("HQF-2210", "1", "9.20"),
    Part("HQF-3007", "1", "142.00"),
    Part("HQF-3011", "3", "11.75"),
]


@dataclass(frozen=True)
class Words:
    """Every word the page draws, in one language.

    The references, the quantities and the prices are not here: they are the same
    figures in every language, and they are what the two narrow columns are measured
    from.
    """

    # The line over each of the two tables.
    captions: tuple[str, str]
    # The four column headings, in the order the columns are drawn.
    headings: tuple[str, str, str, str]
    # What each part is, in the order the rows are drawn.
    descriptions: tuple[str, str, str, str, str]


# The page in English.
ENGLISH = Words(
    captions=(
        "Columns of equal width",
        "Columns measured from their cells",
    ),
    headings=("Reference", "Description", "Qty", "Unit price"),
    descriptions=(
        "Aluminium mounting plate, drilled for the four-point thread",
        "Quick-release shoe",
        "Sealing ring, nitrile, sold in packs of ten",
        "Bench supply, twelve volts, regulated",
        "Adapter lead, two metres",
    ),
)

# The page in French.
FRENCH = Words(
    captions=(
        "Des colonnes de largeur égale",
        "Des colonnes mesurées sur leurs cellules",
    ),
    headings=("Référence", "Désignation", "Qté", "Prix unitaire"),
    descriptions=(
        "Plaque de montage en aluminium, percée pour la fixation quatre points",
        "Sabot à dégagement rapide",
        "Joint torique en nitrile, vendu par dix",
        "Alimentation d'établi, douze volts, régulée",
        "Cordon adaptateur, deux mètres",
    ),
)


# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}


def parts_list(
    font: hqf_pdf.FontHandle, words: Words, columns: hqf_pdf.Columns
) -> hqf_pdf.Table:
    """The parts list, laid out across `columns`."""
    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
    hairline = hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), hairline)
    table.rule(hqf_pdf.Rule.vertical_other(), hairline)
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8))

    pad = hqf_pdf.Padding.symmetric(6.0, 5.0)

    def heading(label: str, align: hqf_pdf.Align = hqf_pdf.Align.Left) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            align=align,
            padding=pad,
            valign=hqf_pdf.VAlign.Middle,
            fill=hqf_pdf.Rgb.gray(0.88),
        )

    table.push(
        hqf_pdf.Row(
            [
                heading(words.headings[0]),
                heading(words.headings[1]),
                heading(words.headings[2], hqf_pdf.Align.Right),
                heading(words.headings[3], hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    for part, description in zip(PARTS, words.descriptions):
        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(font, 9.0, part.reference, padding=pad),
                    hqf_pdf.Cell(font, 9.0, description, padding=pad),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        part.quantity,
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                    ),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        part.price,
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        align_on=".",
                    ),
                ],
                min_height=18.0,
            )
        )

    return table


def caption(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, label: str, y: float
) -> None:
    """Draws `label` at (MARGIN, y) in 11pt."""
    content.draw_text(font, 11.0, MARGIN, y, label)


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(
        Path(_language.file_name("measured_columns.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    # Four columns sharing the width equally, and the same four with three of them
    # measured from their own cells.
    equal = parts_list(font, words, hqf_pdf.Columns.equal(4, TABLE_WIDTH))
    measured = parts_list(
        font,
        words,
        hqf_pdf.Columns(
            [
                hqf_pdf.ColumnWidth.content(),
                hqf_pdf.ColumnWidth.fraction(1.0),
                hqf_pdf.ColumnWidth.content(),
                hqf_pdf.ColumnWidth.content(),
            ],
            TABLE_WIDTH,
        ),
    )

    content = hqf_pdf.Content()

    caption(content, font, words.captions[0], TOP + 18.0)
    first = equal.fit(MARGIN, TOP, TOP - MARGIN, 0)
    first.draw(content)

    second_top = first.bottom - GAP
    caption(content, font, words.captions[1], second_top + 18.0)
    second = measured.fit(MARGIN, second_top, second_top - MARGIN, 0)
    second.draw(content)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {equal.row_count} rows twice")


if __name__ == "__main__":
    main()