A report that lays itself out

A title, a rule, two paragraphs, a heading, a table of twenty-six rows and a footnote, handed over in reading order and broken across two pages by the engine.

Python write_stack.py 289 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
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
"""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é placé contre une "
        "hauteur mesurée à la main : 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 rangée de "
        "titres redessinée en haut de chaque page où il se poursuit. Ce paragraphe, "
        "lui, tient 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 € et les montants s'entendent hors taxes.",
    page="Page",
    of="sur",
)


# 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}

# 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, 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(
            [
                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(
                [
                    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, 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, 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()