Une page qui ne transporte aucune police

Quatre polices que tout lecteur dessine déjà, sur une seule page, donc le fichier n'en contient aucune — et l'exemple pèse les mêmes lignes des deux façons pour dire ce que cela économise.

Python write_no_font_at_all.py 233 lignes
  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
"""Sets a whole page in fonts the file does not carry, and weighs what that saves.

The Python twin of the `write_no_font_at_all` example in Rust. A reader is required to
draw fourteen fonts whether the file carries them or not, so a document that names one
of them writes no font program: a few hundred bytes of dictionary instead of the tens of
kilobytes a subset costs. The page is set in four of them, and the figures it states are
measured by the program, not written in by hand.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

Usage: python examples/write_no_font_at_all.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_no_font_at_all.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 page draws, in one language."""

    # The page's title.
    title: str
    # What the page is about.
    lead: str
    # The label over the four samples.
    faces: str
    # What each of the four samples says.
    samples: tuple[str, str, str, str]
    # The heading over the weight.
    weight: str
    # The sentence the two measured weights are put into.
    saved: str
    # What such a font cannot do.
    caveat: str


# The page in English.
ENGLISH = Words(
    title="A page that carries no font",
    lead=(
        "Every one of the lines below is set in a font this file does not hold. A "
        "reader draws them from its own store, which is what the standard asks of it, "
        "so nothing of the typefaces travels with the document."
    ),
    faces="Four of the fourteen",
    samples=(
        "Helvetica, the one without serifs.",
        "Times Bold Italic, and it is already accented: déjà, ç, ù, ô, ï.",
        "Courier, where every letter is the same width.",
        "Σ √ ∫ αβγ ≥ ∞",
    ),
    weight="What it saves",
    saved=(
        "Those four lines, on a page of their own, weigh %light% bytes. The same four "
        "lines, with one font carried inside the file, weigh %heavy%. Both figures are "
        "measured by the program that drew this page, not written in by hand."
    ),
    caveat=(
        "It is not free. A file claiming an archival or accessibility standard may not "
        "do this — those standards want every font carried — and these faces draw only "
        "the letters their own encoding reaches, so a writing system outside it needs "
        "a font the file does carry."
    ),
)

# The page in French.
FRENCH = Words(
    title="Une page qui ne transporte aucune police",
    lead=(
        "Chacune des lignes ci-dessous est composée dans une police que ce fichier ne "
        "contient pas. Le lecteur les prend dans sa propre réserve, ce que la norme "
        "lui impose, et rien des caractères ne voyage avec le document."
    ),
    faces="Quatre des quatorze",
    samples=(
        "Helvetica, celle qui n'a pas d'empattements.",
        "Times gras italique, et déjà accentuée : ç, ù, ô, ï, œ.",
        "Courier, où chaque lettre occupe la même largeur.",
        "Σ √ ∫ αβγ ≥ ∞",
    ),
    weight="Ce que cela économise",
    saved=(
        "Ces quatre lignes, sur une page à elles seules, pèsent %light% octets. Les "
        "mêmes quatre lignes, avec une police transportée dans le fichier, en pèsent "
        "%heavy%. Les deux chiffres sont mesurés par le programme qui a dessiné cette "
        "page, pas écrits à la main."
    ),
    caveat=(
        "Ce n'est pas gratuit. Un fichier qui réclame une norme d'archivage ou "
        "d'accessibilité n'a pas le droit de faire cela — ces normes veulent toute "
        "police transportée — et ces caractères ne dessinent que les lettres que leur "
        "propre encodage atteint : une écriture en dehors exige une police que le "
        "fichier porte vraiment."
    ),
)


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

# The left edge of everything on the page.
LEFT = 72.0

# How wide a block of text is.
WIDTH = 450.0

# The four the page is set in, in the order it sets them.
FACES = (
    hqf_pdf.StandardFont.helvetica,
    hqf_pdf.StandardFont.times_bold_italic,
    hqf_pdf.StandardFont.courier,
    hqf_pdf.StandardFont.symbol,
)


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def spaced(count: int) -> str:
    """A count with a no-break space between its thousands."""
    digits = str(count)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(" ")
        out.append(digit)
    return "".join(out)


def weighed(words: Words, carried: Path | None) -> int:
    """What a page holding nothing but the four samples weighs.

    This is the measurement the page reports. It is made on a page of its own so that
    the prose around it — and the figures themselves — weigh nothing in it.
    """
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    if carried is None:
        handles = [doc.add_standard_font(face()) for face in FACES]
    else:
        one = doc.add_font(hqf_pdf.Font.from_path(carried))
        handles = [one] * len(words.samples)

    content = hqf_pdf.Content()
    top = 760.0
    for handle, sample in zip(handles, words.samples):
        top = block(content, handle, 13.0, top, sample) - 10.0

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    doc.add_page(page)
    return len(doc.to_bytes())


def build(words: Words, light: int, heavy: int) -> bytes:
    """Draws the whole page, stating the two weights it measured."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    handles = [doc.add_standard_font(face()) for face in FACES]
    text = handles[0]

    content = hqf_pdf.Content()
    top = 760.0
    top = block(content, text, 18.0, top, words.title) - 14.0
    top = block(content, text, 10.0, top, words.lead) - 24.0

    top = block(content, text, 12.0, top, words.faces) - 12.0
    for handle, sample in zip(handles, words.samples):
        top = block(content, handle, 13.0, top, sample) - 10.0

    top -= 14.0
    top = block(content, text, 12.0, top, words.weight) - 10.0
    said = words.saved.replace("%light%", spaced(light)).replace(
        "%heavy%", spaced(heavy)
    )
    top = block(content, text, 10.0, top, said) - 20.0

    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    block(content, text, 9.0, top, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    doc.add_page(page)
    return doc.to_bytes()


def main() -> None:
    """Writes the page."""
    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("no_font_at_all.pdf", language)).stem
    )

    light = weighed(words, None)
    heavy = weighed(words, _out.font_path())
    data = build(words, light, heavy)

    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(data)
    print(f"wrote {out}: {len(data)} bytes")


if __name__ == "__main__":
    main()