write_transparency.py

Die Python-Datei des Beispiels „Transparenz und Füllmethoden“. Halb durchsichtige Füllungen, die sich überlappen und mischen, ein orangefarbenes Quadrat über einem blauen Balken auf vier verschiedene Arten, Farben zu mischen, und eine Zeile sich überlappender Buchstaben, auf zwei Arten gemalt.

Python 380 Zeilen

Wofür dieses Beispiel da ist

Ein Wasserzeichen, das den Text darunter verdeckt, ist nutzlos, und eine Hervorhebung, die nicht durchsichtig ist, ist ein Klecks. Beide wollen dasselbe: Farbe, die das Darunterliegende in einem angegebenen Maß durchscheinen lässt, ohne dass jemand ausrechnen muss, welche Mischfarbe entstünde, und stattdessen diese malt.

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
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
"""Shows three things an extended graphics state opens: half-opacity fills that
overlap and mix, one colour laid over another in four blend modes, and overlapping
letters of one text object knocked out or composited.

The Python twin of the `write_transparency` example in Rust. The opacity panel
draws three rectangles, each at half opacity, so the colours show through one
another where they overlap. The blend panel lays the same orange square over a
blue bar four times, once in each of four modes, so the mode each square is
painted in can be read from the colour it leaves. The knockout panel sets the same
line twice at half opacity, each letter crossed by a stroke that overlaps it: under
`TK true` the text object is painted as one and the overlaps come out as light as the
rest, under `TK false` each glyph is composited on its own and the overlaps come out
darker. A reader that ignores the flag shows the two lines alike.

The second page lays the same square over the same bar in the twelve other blend
modes, then strokes a wide line at half opacity across a fill, once read as an opacity
and once as a shape: the two look alike on a page, and only a knockout group tells them
apart.

The five headings are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. Each square is labelled with the name the file writes for its blend
mode, and each line with the entry its state writes, which are the same in every
language.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge the panels line up on.
X = 80.0

# The line the knockout panel sets twice: each letter followed by a combining stroke
# that takes no room of its own, so the stroke lies across the letter.
CROSSED = "O\u0338O\u0338O\u0338O\u0338"


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

    What is not language stays out of it: each square is labelled with the name the file
    writes for its blend mode, and each crossed line with the entry its state writes.
    """

    # The heading above the opacity panel.
    opacity: str
    # The heading above the blend panel.
    blends: str
    # The heading above the knockout panel.
    knockout: str
    # The heading above the second page's blend panel.
    more_blends: str
    # The heading above the stroke panel.
    strokes: str


# The page in English.
ENGLISH = Words(
    opacity="Half-opacity fills overlap and mix.",
    blends="One orange square over a blue bar, in four blend modes.",
    knockout=(
        "Overlapping letters at half opacity: knocked out on the left, composited "
        "with one another on the right."
    ),
    more_blends=(
        "The same orange square over the same blue bar, in the twelve other blend "
        "modes."
    ),
    strokes=(
        "A wide stroke at half opacity over a fill: an opacity on the left, a shape on "
        "the right."
    ),
)

# The page in French.
FRENCH = Words(
    opacity="Des aplats à moitié transparents se chevauchent et se mélangent.",
    blends="Un carré orange sur une barre bleue, dans quatre modes de fusion.",
    knockout=(
        ("Des lettres qui se chevauchent, à moitié transparentes : en défonce à "
         "gauche, mélangées entre elles à droite.")
    ),
    more_blends=(
        "Le même carré orange sur la même barre bleue, dans les douze autres modes de "
        "fusion."
    ),
    strokes=(
        "Un trait épais à demi transparent sur un aplat : opacité à gauche, forme à "
        "droite."
    ),
)

# The page in Dutch.
DUTCH = Words(
    opacity="Vullingen op halve dekking overlappen en mengen.",
    blends="Eén oranje vierkant over een blauwe balk, in vier overvloeimodi.",
    knockout=(
        "Overlappende letters op halve dekking: links uitgespaard, rechts met elkaar "
        "samengesteld."
    ),
    more_blends=(
        "Hetzelfde oranje vierkant over dezelfde blauwe balk, in de twaalf andere "
        "overvloeimodi."
    ),
    strokes=(
        "Een brede lijn op halve dekking over een vulling: links een dekking, rechts "
        "een vorm."
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    opacity="Preenchimentos a meia opacidade sobrepõem-se e misturam-se.",
    blends="Um quadrado laranja sobre uma barra azul, em quatro modos de mistura.",
    knockout=(
        "Letras sobrepostas a meia opacidade: excluídas à esquerda, compostas entre "
        "si à direita."
    ),
    more_blends=(
        "O mesmo quadrado laranja sobre a mesma barra azul, nos outros doze modos de "
        "mistura."
    ),
    strokes=(
        "Traço largo semiopaco sobre um fundo: uma opacidade à esquerda, uma forma à "
        "direita."
    ),
)

# The page in Italian.
ITALIAN = Words(
    opacity="Riempimenti a metà opacità si sovrappongono e si mescolano.",
    blends="Un quadrato arancione su una barra blu, in quattro metodi di fusione.",
    knockout=(
        "Lettere sovrapposte a metà opacità: escluse a sinistra, composte tra loro a "
        "destra."
    ),
    more_blends=(
        "Lo stesso quadrato arancione sulla stessa barra blu, negli altri dodici "
        "metodi di fusione."
    ),
    strokes=(
        "Un tratto largo a metà opacità su un riempimento: un’opacità a sinistra, una "
        "forma a destra."
    ),
)

# The page in Spanish.
SPANISH = Words(
    opacity="Rellenos a media opacidad se superponen y se mezclan.",
    blends="Un cuadrado naranja sobre una barra azul, en cuatro modos de fusión.",
    knockout=(
        "Letras superpuestas a media opacidad: excluidas a la izquierda, compuestas "
        "entre sí a la derecha."
    ),
    more_blends=(
        "El mismo cuadrado naranja sobre la misma barra azul, en los otros doce modos "
        "de fusión."
    ),
    strokes=(
        "Trazo ancho semiopaco sobre un relleno: una opacidad a la izquierda, una "
        "forma a la derecha."
    ),
)

# The page in German.
GERMAN = Words(
    opacity="Halbdeckende Flächen überlappen und mischen sich.",
    blends="Ein orangefarbenes Quadrat über einem blauen Balken, in vier Mischmodi.",
    knockout=(
        "Überlappende Buchstaben mit halber Deckkraft: links ausgespart, rechts "
        "miteinander verrechnet."
    ),
    more_blends=(
        "Dasselbe orangefarbene Quadrat über demselben blauen Balken, in den zwölf "
        "anderen Mischmodi."
    ),
    strokes=(
        "Ein breiter Strich mit halber Deckkraft über einer Fläche: links eine "
        "Deckkraft, rechts eine Form."
    ),
)


# 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 heading(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    top: float,
    label: str,
    left: float,
) -> None:
    """Sets a one-line label with its baseline at top, left edge at left."""
    flow = hqf_pdf.TextFlow(handle, 8.0)
    lines = flow.break_lines(label, 400.0)
    flow.draw(content, lines, left, top, 400.0)


def second_page(
    document: hqf_pdf.Document, handle: hqf_pdf.FontHandle, words: Words
) -> hqf_pdf.Content:
    """The second page: the twelve other blend modes, four to a row, and a wide
    stroke at half opacity read two ways."""
    modes = (
        ("Overlay", hqf_pdf.BlendMode.Overlay),
        ("Darken", hqf_pdf.BlendMode.Darken),
        ("Lighten", hqf_pdf.BlendMode.Lighten),
        ("ColorDodge", hqf_pdf.BlendMode.ColorDodge),
        ("ColorBurn", hqf_pdf.BlendMode.ColorBurn),
        ("HardLight", hqf_pdf.BlendMode.HardLight),
        ("SoftLight", hqf_pdf.BlendMode.SoftLight),
        ("Exclusion", hqf_pdf.BlendMode.Exclusion),
        ("Hue", hqf_pdf.BlendMode.Hue),
        ("Saturation", hqf_pdf.BlendMode.Saturation),
        ("Color", hqf_pdf.BlendMode.Color),
        ("Luminosity", hqf_pdf.BlendMode.Luminosity),
    )
    strokes = (
        ("CA 0.5", hqf_pdf.ExtGState(stroke_alpha=0.5)),
        ("CA 0.5 AIS true", hqf_pdf.ExtGState(stroke_alpha=0.5, alpha_is_shape=True)),
    )

    content = hqf_pdf.Content()
    heading(content, handle, 780.0, words.more_blends, X)
    square = 80.0
    gap = 20.0
    bottom = 640.0
    for first in range(0, len(modes), 4):
        left = X
        for label, mode in modes[first : first + 4]:
            state = document.add_ext_gstate(hqf_pdf.ExtGState(blend_mode=mode))
            content.set_fill(hqf_pdf.Rgb(0.15, 0.35, 0.80))
            content.rect(left, bottom + 20.0, square, square)
            content.fill()
            content.save_state()
            content.set_ext_gstate(state)
            content.set_fill(hqf_pdf.Rgb(0.95, 0.55, 0.10))
            content.rect(left + 20.0, bottom, square, square)
            content.fill()
            content.restore_state()
            heading(content, handle, bottom - 10.0, label, left)
            left += square + gap
        bottom -= 150.0

    heading(content, handle, 260.0, words.strokes, X)
    left = X
    for label, state in strokes:
        added = document.add_ext_gstate(state)
        content.set_fill(hqf_pdf.Rgb(0.15, 0.35, 0.80))
        content.rect(left, 130.0, 160.0, 90.0)
        content.fill()
        content.save_state()
        content.set_ext_gstate(added)
        content.set_stroke(hqf_pdf.Rgb(0.95, 0.55, 0.10))
        content.set_line_width(24.0)
        content.move_to(left - 10.0, 110.0)
        content.line_to(left + 170.0, 240.0)
        content.stroke()
        content.restore_state()
        heading(content, handle, 95.0, label, left)
        left += 220.0
    return content


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

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

    # The states the three panels apply, added once and shared.
    half = document.add_ext_gstate(hqf_pdf.ExtGState(fill_alpha=0.5))
    modes = (
        ("Normal", hqf_pdf.BlendMode.Normal),
        ("Multiply", hqf_pdf.BlendMode.Multiply),
        ("Screen", hqf_pdf.BlendMode.Screen),
        ("Difference", hqf_pdf.BlendMode.Difference),
    )
    blends = [
        (label, document.add_ext_gstate(hqf_pdf.ExtGState(blend_mode=mode)))
        for label, mode in modes
    ]
    knockouts = (
        (
            "TK true",
            document.add_ext_gstate(
                hqf_pdf.ExtGState(fill_alpha=0.5, text_knockout=True)
            ),
        ),
        (
            "TK false",
            document.add_ext_gstate(
                hqf_pdf.ExtGState(fill_alpha=0.5, text_knockout=False)
            ),
        ),
    )

    content = hqf_pdf.Content()

    # The opacity panel: three overlapping rectangles, each at half opacity.
    heading(content, handle, 720.0, words.opacity, X)
    colors = (
        (0.0, hqf_pdf.Rgb(0.85, 0.15, 0.15)),
        (30.0, hqf_pdf.Rgb(0.15, 0.65, 0.20)),
        (60.0, hqf_pdf.Rgb(0.15, 0.30, 0.85)),
    )
    for offset, color in colors:
        content.save_state()
        content.set_ext_gstate(half)
        content.set_fill(color)
        content.rect(X + offset, 590.0, 90.0, 90.0)
        content.fill()
        content.restore_state()

    # The blend panel: an orange square over a blue bar, once per mode.
    heading(content, handle, 520.0, words.blends, X)
    square = 80.0
    gap = 20.0
    left = X
    for label, state in blends:
        content.set_fill(hqf_pdf.Rgb(0.15, 0.35, 0.80))
        content.rect(left, 380.0, square, square)
        content.fill()
        content.save_state()
        content.set_ext_gstate(state)
        content.set_fill(hqf_pdf.Rgb(0.95, 0.55, 0.10))
        content.rect(left + 20.0, 360.0, square, square)
        content.fill()
        content.restore_state()
        heading(content, handle, 350.0, label, left)
        left += square + gap

    # The knockout panel: the crossed line twice, the state applied before the text
    # object opens, since a text object reads the flag as it begins.
    heading(content, handle, 300.0, words.knockout, X)
    crossed = hqf_pdf.TextFlow(handle, 48.0, color=hqf_pdf.Rgb(0.15, 0.30, 0.85))
    lines = crossed.break_lines(CROSSED, 200.0)
    left = X
    for label, state in knockouts:
        content.save_state()
        content.set_ext_gstate(state)
        crossed.draw(content, lines, left, 280.0, 200.0)
        content.restore_state()
        heading(content, handle, 210.0, label, left)
        left += 200.0

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    page = hqf_pdf.Page.a4()
    page.set_content(second_page(document, handle, words))
    document.add_page(page)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()