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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433 | """Lays a whole report out by stacking blocks, without writing a single ordinate
by hand.
The Python twin of the `write_stack` example in Rust. The page holds a title, a
rule, two paragraphs, a heading, a table of twenty-six rows and a footnote, and
they are pushed onto a stack in the order they are read. The stack breaks them
across as many pages as they need: the table is cut row by row, its heading row
repeated, and the closing paragraph is kept together so that it is never left
with one line on a page of its own.
The only ordinate the example writes is the one the page number sits on, which
belongs to the sheet rather than to what is said on it.
Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The hours and the amounts are figures, and stand the same in every language.
Usage: python examples/write_stack.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_stack.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
@dataclass(frozen=True)
class Words:
"""Every word the report draws, in one language.
What is not language stays out of it: every hour and every amount is a figure, and
the row numbers run from one whatever the words say.
"""
# The report's title.
title: str
# The paragraph under the title.
intro: str
# The heading over the table.
section: str
# The three column headings of the table.
headings: tuple[str, str, str]
# What each row of the table is called, before its number.
task: str
# The paragraph under the table, kept together.
closing: str
# The line at the foot of the report.
footnote: str
# The word the page number opens with.
page: str
# The word between a page's number and how many pages there are.
of: str
def page_label(self, index: int, total: int) -> str:
"""Return what the foot of page `index` of `total` reads."""
return f"{self.page} {index + 1} {self.of} {total}"
def row_label(self, index: int) -> str:
"""Return what row `index` of the table is called."""
return f"{self.task} {index + 1:02d}"
# The report in English.
ENGLISH = Words(
title="Work carried out this quarter",
intro=(
"Every block on this page was pushed onto a stack in the order it is read, and "
"the stack decided where each of them goes. Nothing here was placed against a "
"measured height: a paragraph that grows pushes what follows it down the page, "
"and onto the next one when the room runs out."
),
section="What was done, task by task",
headings=(
"Task",
"Hours",
"Amount",
),
task="Task",
closing=(
"The table above was cut wherever the room ran out, and its heading row was "
"drawn again at the top of every page it was carried onto. This paragraph was "
"kept together, so it is never left with a single line at the foot of a page "
"while the rest of it starts the next one."
),
footnote="Hours are billed at 85.00 € each, and the amounts are exclusive of tax.",
page="Page",
of="of",
)
# The report in French.
FRENCH = Words(
title="Les travaux du trimestre",
intro=(
"Chaque bloc de cette page a été empilé dans l’ordre où on le lit, et c’est la "
"pile qui a décidé où chacun se pose. Rien n’a été positionné d’après une "
"hauteur mesurée d’avance : un paragraphe qui s’allonge pousse la suite vers "
"le bas, et sur la page suivante quand la place vient à manquer."
),
section="Le détail, tâche par tâche",
headings=(
"Tâche",
"Heures",
"Montant",
),
task="Tâche",
closing=(
"Le tableau ci-dessus a été coupé là où la place manquait, et sa ligne "
"d’en-tête répétée en haut de chaque page où il se poursuit. Ce paragraphe, "
"lui, reste d’un seul tenant : il ne laisse jamais une ligne seule en bas "
"d’une page pendant que le reste ouvre la suivante."
),
footnote="L’heure est facturée 85.00 EUR et les montants s’entendent hors taxes.",
page="Page",
of="sur",
)
# The report in Dutch.
DUTCH = Words(
title="Dit kwartaal uitgevoerd werk",
intro=(
"Elk blok op deze pagina is op een stapel gelegd in de volgorde waarin het "
"gelezen wordt, en de stapel besliste waar elk terechtkomt. Niets hier is "
"tegen een gemeten hoogte geplaatst: een alinea die groeit, duwt wat volgt de "
"pagina af, en naar de volgende als de ruimte op is."
),
section="Wat er gedaan is, taak voor taak",
headings=(
"Taak",
"Uren",
"Bedrag",
),
task="Taak",
closing=(
"De tabel hierboven is gesneden waar de ruimte op was, en haar koprij is "
"opnieuw getekend bovenaan elke pagina waarnaar ze doorliep. Deze alinea is "
"bij elkaar gehouden, dus blijft ze nooit met één regel onderaan een pagina "
"achter terwijl de rest op de volgende begint."
),
footnote="Uren worden gefactureerd tegen EUR 85,00 per uur, en de bedragen zijn exclusief btw.",
page="Pagina",
of="van",
)
# The report in Portuguese.
PORTUGUESE = Words(
title="Trabalho feito este trimestre",
intro=(
"Cada bloco desta página foi empilhado pela ordem em que se lê, e a pilha "
"decidiu onde vai cada um. Nada aqui foi colocado contra uma altura medida: "
"um parágrafo que cresce empurra o que se segue pela página abaixo, e para a "
"seguinte quando o espaço acaba."
),
section="O que foi feito, tarefa a tarefa",
headings=(
"Tarefa",
"Horas",
"Montante",
),
task="Tarefa",
closing=(
"A tabela acima foi cortada onde o espaço acabou, e a sua linha de títulos "
"foi redesenhada no topo de cada página para onde passou. Este parágrafo foi "
"mantido junto, por isso nunca fica com uma só linha no fundo de uma página "
"enquanto o resto começa a seguinte."
),
footnote="As horas são faturadas a 85,00 € cada, e os montantes não incluem impostos.",
page="Página",
of="de",
)
# The report in Italian.
ITALIAN = Words(
title="Lavoro svolto questo trimestre",
intro=(
"Ogni blocco di questa pagina è stato impilato nell’ordine in cui si legge, e "
"la pila ha deciso dove va ciascuno. Niente è stato collocato contro "
"un’altezza misurata: un paragrafo che cresce spinge ciò che segue giù per la "
"pagina, e sulla successiva quando lo spazio finisce."
),
section="Cosa si è fatto, attività per attività",
headings=(
"Attività",
"Ore",
"Importo",
),
task="Attività",
closing=(
"La tabella qui sopra è stata tagliata dove lo spazio finiva, e la sua riga "
"di intestazione è stata ridisegnata in cima a ogni pagina su cui è "
"proseguita. Questo paragrafo è stato tenuto unito, così non resta mai con "
"una sola riga a piè di pagina mentre il resto inizia la successiva."
),
footnote="Le ore sono fatturate a 85,00 € ciascuna, e gli importi si intendono al netto delle imposte.",
page="Pagina",
of="di",
)
# The report in Spanish.
SPANISH = Words(
title="Trabajo realizado este trimestre",
intro=(
"Cada bloque de esta página se apiló en el orden en que se lee, y la pila "
"decidió dónde va cada uno. Nada se colocó contra una altura medida: un "
"párrafo que crece empuja lo que le sigue página abajo, y a la siguiente "
"cuando se acaba el sitio."
),
section="Qué se hizo, tarea a tarea",
headings=(
"Tarea",
"Horas",
"Importe",
),
task="Tarea",
closing=(
"La tabla de arriba se cortó donde se acabó el sitio, y su fila de títulos se "
"volvió a dibujar arriba de cada página a la que pasó. Este párrafo se "
"mantuvo junto, así que nunca queda con una sola línea al pie de una página "
"mientras el resto empieza la siguiente."
),
footnote="Las horas se facturan a 85,00 € cada una, y los importes no incluyen impuestos.",
page="Página",
of="de",
)
# The report in German.
GERMAN = Words(
title="In diesem Quartal ausgeführte Arbeiten",
intro=(
"Jeder Block auf dieser Seite wurde in der Lesereihenfolge auf einen Stapel "
"gelegt, und der Stapel hat entschieden, wohin jeder kommt. Nichts hier wurde "
"gegen eine gemessene Höhe platziert: Ein wachsender Absatz schiebt das "
"Folgende die Seite hinunter und auf die nächste, wenn der Platz ausgeht."
),
section="Was erledigt wurde, Aufgabe für Aufgabe",
headings=(
"Aufgabe",
"Stunden",
"Betrag",
),
task="Aufgabe",
closing=(
"Die Tabelle oben wurde dort getrennt, wo der Platz ausging, und ihre "
"Kopfzeile wurde oben auf jeder Seite, auf die sie weiterlief, erneut "
"gezeichnet. Dieser Absatz wurde zusammengehalten, also bleibt nie eine "
"einzelne Zeile unten auf einer Seite zurück, während der Rest die nächste "
"beginnt."
),
footnote="Stunden werden mit je 85,00 € berechnet, und die Beträge verstehen sich ohne Steuer.",
page="Seite",
of="von",
)
# 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}
# How many rows of work the table carries.
ROWS = 26
# The colour of the rule under the title.
ACCENT = hqf_pdf.Rgb(0.12, 0.33, 0.55)
# The colour the footnote and the page number are set in.
MUTED = hqf_pdf.Rgb(0.45, 0.45, 0.45)
# How wide the report is, in points: the sheet less a margin either side.
WIDTH = 483.0
# The left edge of everything the report draws.
LEFT = 56.0
# The ordinate the page number sits on, which belongs to the sheet rather than to what
# is said on it.
FOOT = 40.0
# The box the first page gives the report, and the one every page after it gives.
FIRST_BOX = hqf_pdf.StackFrame(LEFT, 780.0, WIDTH, 700.0)
NEXT_BOX = hqf_pdf.StackFrame(LEFT, 780.0, WIDTH, 700.0)
def work(index: int) -> tuple[int, int]:
"""Return the hours row `index` took, and what they came to."""
hours = 2 + index % 5
return hours, hours * 85
def work_table(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
"""Return the table of work, its heading row repeated on every page."""
columns = hqf_pdf.Columns(
[
hqf_pdf.ColumnWidth.fraction(1.0),
hqf_pdf.ColumnWidth.points(70.0),
hqf_pdf.ColumnWidth.points(90.0),
],
WIDTH,
)
table = hqf_pdf.Table(columns)
table.header(1)
table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
table.rule(
hqf_pdf.Rule.horizontal_other(),
hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.75)),
)
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.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], hqf_pdf.Align.Left),
heading(words.headings[1], hqf_pdf.Align.Right),
heading(words.headings[2], hqf_pdf.Align.Right),
],
min_height=20.0,
)
)
for index in range(ROWS):
hours, amount = work(index)
table.push(
hqf_pdf.Row(
cells=[
hqf_pdf.Cell(font, 9.0, words.row_label(index), padding=pad),
hqf_pdf.Cell(
font, 9.0, f"{hours}", align=hqf_pdf.Align.Right, padding=pad
),
hqf_pdf.Cell(
font,
9.0,
f"{amount}.00",
align=hqf_pdf.Align.Right,
padding=pad,
),
]
)
)
return table
def report(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Stack:
"""Return the whole report, block by block, in the order it is read."""
body = hqf_pdf.TextFlow(font, 10.5, leading=15.0, align=hqf_pdf.Align.Justify)
stack = hqf_pdf.Stack()
stack.push(
hqf_pdf.Block.text(
hqf_pdf.TextFlow(font, 16.0), words.title, keep_together=True
)
)
stack.push(hqf_pdf.Block.space(8.0))
stack.push(hqf_pdf.Block.rule(hqf_pdf.Stroke(1.2, color=ACCENT)))
stack.push(hqf_pdf.Block.space(14.0))
stack.push(hqf_pdf.Block.text(body, words.intro))
stack.push(hqf_pdf.Block.space(18.0))
stack.push(
hqf_pdf.Block.text(
hqf_pdf.TextFlow(font, 12.0), words.section, keep_together=True
)
)
stack.push(hqf_pdf.Block.space(8.0))
stack.push(hqf_pdf.Block.table(work_table(font, words)))
stack.push(hqf_pdf.Block.space(18.0))
stack.push(hqf_pdf.Block.text(body, words.closing, keep_together=True))
stack.push(hqf_pdf.Block.space(14.0))
stack.push(hqf_pdf.Block.rule(hqf_pdf.Stroke(0.6, color=MUTED)))
stack.push(hqf_pdf.Block.space(8.0))
stack.push(
hqf_pdf.Block.text(hqf_pdf.TextFlow(font, 8.0, color=MUTED), words.footnote)
)
return stack
def page_number(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
words: Words,
index: int,
total: int,
) -> None:
"""Draw the page number at the foot of the sheet."""
flow = hqf_pdf.TextFlow(font, 8.0, color=MUTED, align=hqf_pdf.Align.Center)
label = words.page_label(index, total)
flow.draw(content, flow.break_lines(label, WIDTH), LEFT, FOOT, WIDTH)
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("stack.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
pages = report(font, words).paginate(FIRST_BOX, NEXT_BOX)
for index, placed in enumerate(pages):
content = hqf_pdf.Content()
placed.draw(content)
page_number(content, font, words, index, len(pages))
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes")
if __name__ == "__main__":
main()
|