write_flow_break.py

Die Python-Datei des Beispiels „Ein überlanges Wort umbrechen“. Ein Wort, länger als die Spalte, die es enthält: Die Bibliothek lässt es ganz, schneidet es am Rand der Spalte ab oder schneidet es ab und schließt die Zeile mit einem Bindestrich.

Python 192 Zeilen

Wofür dieses Beispiel da ist

Dieses Beispiel setzt denselben Absatz dreimal in eine Spalte, die für eines seiner Wörter zu schmal ist: Jedes Layout trifft irgendwann auf das Wort, das nicht passt — einen chemischen Namen, ein deutsches Kompositum, eine Webadresse, eine Bestellreferenz, an die niemand gedacht hat. Das Wort taucht im Betrieb auf, in einem Datensatz von tausend, lange nachdem das Team das Layout abgenommen hat, und es kommt mit der nächsten Referenz wieder, welche Breite die Spalte auch erhält. Die Einstellung für überlange Wörter entscheidet: overflow lässt das ganze Wort über den Rand laufen, break schneidet es nach der letzten passenden Glyphe ab, und eine Schnittmarke, wo eine angegeben ist, schließt jede Zeile, an der ein Schnitt endet, mit einem Bindestrich.

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
"""Sets one paragraph in a column too narrow for a word in it, three times: as it
comes, cut to the column, and cut with a hyphen ending each cut line.

The Python twin of the `write_flow_break` example in Rust.

The paragraph and the three headings are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn. Each heading opens with the name the library
gives its setting, which is the same in every language.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The payment reference the paragraph carries: one word to a line breaker, longer than
# the column it is put in, and the same in every language.
REFERENCE = "GB29NWBK60161331926819-2026-07-DEPOSIT"


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

    What is not language stays out of it: the payment reference reads the same wherever
    the page is read, and each heading opens with the name the library gives the setting
    it stands over.
    """

    # The heading over the setting that leaves the long word whole.
    overflow: str
    # The heading over the setting that cuts it.
    breaking: str
    # The heading over the setting that cuts it and marks each cut.
    marked: str
    # The paragraph, cut where the reference goes into it.
    paragraph_before: str
    paragraph_after: str

    def paragraph(self) -> str:
        """Return the paragraph both settings are given, with the reference in it."""
        return f"{self.paragraph_before}{REFERENCE}{self.paragraph_after}"


# The page in English.
ENGLISH = Words(
    overflow="Overflow: the word is left whole, and runs past the edge.",
    breaking="Break: the word is cut after its last glyph that fits.",
    marked="Break with a cut mark: each line the cut closes ends on a hyphen.",
    paragraph_before="Paid by bank transfer, reference ",
    paragraph_after=(
        ", to be matched against the purchase order before the accounts are closed."
    ),
)

# The page in French.
FRENCH = Words(
    overflow="Débordement : le mot reste entier et dépasse le bord.",
    breaking="Coupure : le mot est coupé après le dernier glyphe qui tient.",
    marked=("Coupure avec marque de coupure : chaque ligne coupée finit par un trait "
            "d’union."),
    paragraph_before="Réglé par virement, référence ",
    paragraph_after=", à rapprocher du bon de commande avant la clôture des comptes.",
)

# The page in Dutch.
DUTCH = Words(
    overflow="Overlopen: het woord blijft heel en loopt over de rand.",
    breaking="Afbreken: het woord wordt na zijn laatste passende glyph afgebroken.",
    marked="Afbreken met koppelteken: elke afgebroken regel eindigt op een koppelteken.",
    paragraph_before="Betaald per overschrijving, kenmerk",
    paragraph_after=(
        ", af te stemmen met de inkooporder voordat de boeken worden afgesloten."
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    overflow="Transbordar: a palavra fica inteira e sai da margem.",
    breaking="Quebrar: a palavra é cortada após o último glifo que cabe.",
    marked="Quebrar com marca: cada linha que o corte fecha acaba num hífen.",
    paragraph_before="Pago por transferência, referência",
    paragraph_after=(
        ", a conferir com a nota de encomenda antes do fecho de contas."
    ),
)

# The page in Italian.
ITALIAN = Words(
    overflow="Sborda: la parola resta intera ed esce dal bordo.",
    breaking="Spezza: la parola è tagliata dopo l’ultimo glifo che ci sta.",
    marked="Spezza con segno: ogni riga chiusa dal taglio finisce con un trattino.",
    paragraph_before="Pagato con bonifico, riferimento",
    paragraph_after=(
        ", da confrontare con l’ordine d’acquisto prima della chiusura dei conti."
    ),
)

# The page in Spanish.
SPANISH = Words(
    overflow="Desbordar: la palabra queda entera y sale del borde.",
    breaking="Cortar: la palabra se corta tras el último glifo que cabe.",
    marked="Cortar con marca: cada línea cortada acaba en guion.",
    paragraph_before="Pagado por transferencia, referencia ",
    paragraph_after=(
        ", que se cotejará con la orden de compra antes del cierre contable."
    ),
)

# The page in German.
GERMAN = Words(
    overflow="Überlauf: Das Wort bleibt ganz und läuft über den Rand hinaus.",
    breaking="Umbruch: Das Wort wird nach seinem letzten passenden Glyphen getrennt.",
    marked="Umbruch mit Trennzeichen: Jede getrennte Zeile endet auf einem Bindestrich.",
    paragraph_before="Bezahlt per Banküberweisung, Verwendungszweck ",
    paragraph_after=(
        ", vor dem Abschluss der Bücher mit der Bestellung abzugleichen."
    ),
)


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

COLUMN = 150.0

# The left edge of both columns. They are stacked rather than set side by side, so that
# the overflowing line runs out into the margin and not through the text of the other
# setting.
X = 80.0


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

    # 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("flow_break.pdf", language)).stem)

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

    content = hqf_pdf.Content()

    for top, label, overlong, mark in (
        (760.0, words.overflow, hqf_pdf.Overlong.Overflow, None),
        (620.0, words.breaking, hqf_pdf.Overlong.Break, None),
        (480.0, words.marked, hqf_pdf.Overlong.Break, "-"),
    ):
        heading = hqf_pdf.TextFlow(handle, 8.0)
        heading_lines = heading.break_lines(label, 400.0)
        heading.draw(content, heading_lines, X, top, 400.0)

        text_top = top - 20.0
        flow = hqf_pdf.TextFlow(
            handle, 11.0, leading=15.0, overlong=overlong, cut_mark=mark
        )
        lines = flow.break_lines(paragraph, COLUMN)
        flow.draw(content, lines, X, text_top, COLUMN)

        # The column's edge, to show what each setting does about it.
        height = flow.height(lines)
        content.save_state()
        content.set_stroke(hqf_pdf.Rgb.gray(0.8))
        content.set_line_width(0.5)
        content.rect(X, text_top - height, COLUMN, height)
        content.stroke()
        content.restore_state()

    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()