write_measured_columns.py

Die Python-Datei des Beispiels „An ihren Zellen gemessene Spalten“. Eine Teileliste zweimal: vier Spalten, die sich die Breite gleichmäßig teilen, dann Referenz, Menge und Preis jeweils so breit wie ihre eigene breiteste Zelle und die Beschreibung mit allem, was sie übrig lassen.

Python 317 Zeilen

Wofür dieses Beispiel da ist

Eine Tabelle, deren Spalten gleiche Anteile der Breite erhalten haben, erkennt man auf einen Blick, und nicht im Guten: Die Referenzen und Zahlen sitzen im Dreifachen des Platzes, den sie brauchen, während die Beschreibungen aus Platzmangel umbrechen. Das naheliegende Mittel ist, die Breiten von Hand einzutragen, und es hält bis zu dem Tag, an dem eine Teilenummer länger wird.

Was dieses Beispiel zeigt

  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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""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 de laboratoire, douze volts, régulée",
        "Cordon adaptateur, deux mètres",
    ),
)

# The page in Dutch.
DUTCH = Words(
    captions=(
        "Kolommen van gelijke breedte",
        "Kolommen gemeten naar hun cellen",
    ),
    headings=("Referentie", "Omschrijving", "Aantal", "Stukprijs"),
    descriptions=(
        "Aluminium montageplaat, geboord voor de vierpuntsschroefdraad",
        "Snelkoppelingsschoen",
        "Afdichtring, nitril, per tien verpakt",
        "Labvoeding, twaalf volt, gestabiliseerd",
        "Adapterkabel, twee meter",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    captions=(
        "Colunas de largura igual",
        "Colunas medidas pelas suas células",
    ),
    headings=("Referência", "Descrição", "Qtd.", "Preço unitário"),
    descriptions=(
        "Placa de montagem em alumínio, furada para a rosca de quatro pontos",
        "Sapata de desengate rápido",
        "Anel de vedação, nitrilo, em embalagens de dez",
        "Fonte de bancada, doze volts, regulada",
        "Cabo adaptador, dois metros",
    ),
)

# The page in Italian.
ITALIAN = Words(
    captions=(
        "Colonne di uguale larghezza",
        "Colonne misurate dalle loro celle",
    ),
    headings=("Riferimento", "Descrizione", "Qtà", "Prezzo unitario"),
    descriptions=(
        "Piastra di montaggio in alluminio, forata per la filettatura a quattro punti",
        "Slitta a sgancio rapido",
        "Anello di tenuta, nitrile, in confezioni da dieci",
        "Alimentatore da banco, dodici volt, stabilizzato",
        "Cavo adattatore, due metri",
    ),
)

# The page in Spanish.
SPANISH = Words(
    captions=(
        "Columnas de igual ancho",
        "Columnas medidas por sus celdas",
    ),
    headings=("Referencia", "Descripción", "Cant.", "Precio unitario"),
    descriptions=(
        "Placa de montaje de aluminio, taladrada para la rosca de cuatro puntos",
        "Zapata de liberación rápida",
        "Junta tórica, nitrilo, en paquetes de diez",
        "Fuente de banco, doce voltios, regulada",
        "Cable adaptador, dos metros",
    ),
)

# The page in German.
GERMAN = Words(
    captions=(
        "Spalten gleicher Breite",
        "Spalten, nach ihren Zellen gemessen",
    ),
    headings=("Referenz", "Beschreibung", "Menge", "Einzelpreis"),
    descriptions=(
        "Montageplatte aus Aluminium, für das Vierpunktgewinde gebohrt",
        "Schnellwechselschuh",
        "Dichtring, Nitril, im Zehnerpack",
        "Labornetzteil, zwölf Volt, geregelt",
        "Adapterkabel, zwei Meter",
    ),
)


# 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, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


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, color=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(
            cells=[
                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(
                cells=[
                    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()