write_fitted.py

Die Python-Datei des Beispiels „Ein in ein Rechteck eingepasstes Bild“. Ein Bild, auf acht Arten in ein Rechteck einer Größe eingepasst: drei Arten, es zu bemessen, dasselbe in die linke obere Ecke gestellt mit einem Einzug von 12 Punkt, eine Vierteldrehung nach links, eine Vierteldrehung nach rechts, eine Drehung um 20 Grad und eine Spiegelung von links nach rechts — jedes Feld zeichnet das Bild an der Stelle und in der Größe, die die Bibliothek berechnet hat. Eine zweite Seite fügt acht weitere hinzu: das Bild in seiner eigenen Größe, dann doppelt so groß und dort abgeschnitten, wo es übersteht; nur verkleinert, wenn es zu groß ist; an neun Positionen zugleich gesetzt; ein Viertel nach innen und nach unten platziert; um eine halbe Drehung gedreht; und von oben nach unten gespiegelt.

Python 454 Zeilen

Wofür dieses Beispiel da ist

Ein Bild von außen hat selten die Proportionen des Rechtecks, in das es muss. Auf das Rechteck gestreckt, verliert es seine Proportionen; in seiner eigenen Größe belassen, lässt es leeren Raum um sich oder läuft über den Rand. Diese Entscheidung stellt sich bei jedem Katalog und jedem Bericht neu, den Sie erzeugen.

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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""Fits one picture into boxes of one size eight ways, and labels each.

The Python twin of the `write_fitted` example in Rust. A `FitBox` says how a picture
is sized to a box, where it sits in it, how far the box is inset first, and how far
the picture is turned and mirrored on its way in. Every panel hands the same picture
and the same box to a different policy, and draws what comes back the same way:
concatenate the matrix the policy gives, then draw the picture at the origin at its
natural size. No panel computes the scale or the offset of its picture itself.

The panel that covers its box is the one case that overflows on purpose, so it is
clipped to the box it covers; every other panel stays inside.

A second page lays out eight more: the picture at its natural size, then twice as large
and clipped; shrunk to fit when it is twice as large, and left as it is when it is half
as large; a quarter as large at each of the nine named anchors; half as large at a point
a quarter in from the left and a quarter down, upright and unmirrored; turned upside
down; and mirrored top to bottom. Those panels hand the policy the picture's size
multiplied by the panel's scale, and draw the picture at that size.

The title and the eight captions are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn. The first four captions open with the name
the library gives the policy they describe — ``contain``, ``cover``, ``stretch`` —
which is the same in every language.

Usage: python examples/write_fitted.py [out.pdf]
       HQF_PDF_LANG=fr python examples/write_fitted.py
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The picture every panel fits: the JPEG committed for the tests.
IMAGES = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images"
PHOTO = IMAGES / "photo.jpg"

PAGE_WIDTH = 595.276
MARGIN = 56.0
# The gap between the two columns of panels.
GAP = 24.0
# The box every panel fits its picture into.
BOX_WIDTH = (PAGE_WIDTH - 2.0 * MARGIN - GAP) / 2.0
BOX_HEIGHT = 130.0
# The top of the first row of boxes, and the drop from one row to the next.
FIRST_ROW = 750.0
ROW_PITCH = 176.0
# How far under a box its caption's baseline sits.
CAPTION_DROP = 14.0


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

    The first four captions open with the name the library gives the policy they
    describe — ``contain``, ``cover``, ``stretch`` — and those names are the same
    in every language.
    """

    # The line at the head of the page.
    title: str
    # What is written under each box, in the order the panels are laid out.
    captions: tuple[str, str, str, str, str, str, str, str]
    # The line at the head of the second page.
    more_title: str
    # What is written under each box of the second page, in the order `more_panels` lays
    # them out.
    more_captions: tuple[str, str, str, str, str, str, str, str]


# The page in English.
ENGLISH = Words(
    title="One picture, one box, eight fitting policies",
    captions=(
        "contain: as large as fits, its shape kept",
        "cover: no gap left, the overflow clipped",
        "stretch: the box filled, its shape lost",
        "contain, top left, inset 12 points",
        "a quarter turn anticlockwise",
        "a quarter turn clockwise",
        "turned 20 degrees, still inside its box",
        "mirrored left to right",
    ),
    more_title="The same picture, sized and placed other ways",
    more_captions=(
        "natural: its own size, whatever the box",
        "natural, twice as large, what hangs over clipped",
        "shrink to fit, twice as large: made smaller",
        "shrink to fit, half as large: left, mirrored both ways",
        "natural, a quarter as large, at the nine anchors",
        "a quarter in from the left and a quarter down",
        "a half turn",
        "mirrored top to bottom",
    ),
)

# The page in French.
FRENCH = Words(
    title="Une image, une boîte, huit façons de l’ajuster",
    captions=(
        "contain : aussi grande que possible, proportions gardées",
        "cover : aucun vide laissé, le débordement rogné",
        "stretch : la boîte remplie, les proportions perdues",
        "contain, en haut à gauche, 12 points de retrait",
        "un quart de tour, sens antihoraire",
        "un quart de tour, sens horaire",
        "tournée de 20 degrés, toujours dans sa boîte",
        "inversée de gauche à droite",
    ),
    more_title="La même image, dimensionnée et placée autrement",
    more_captions=(
        "natural : à sa propre taille, quelle que soit la boîte",
        "natural, deux fois plus grande, le débordement rogné",
        "shrink to fit, deux fois plus grande : réduite",
        "shrink to fit, demi-taille : à gauche, double miroir",
        "natural, quatre fois moins grande, aux neuf ancres",
        "à un quart du bord gauche et à un quart du haut",
        "un demi-tour",
        "en miroir de haut en bas",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Eén afbeelding, één kader, acht manieren van passen",
    captions=(
        "contain: zo groot als past, vorm behouden",
        "cover: geen gat, het overschot afgesneden",
        "stretch: het kader gevuld, de vorm kwijt",
        "contain, linksboven, 12 punten ingesprongen",
        "een kwartslag tegen de klok in",
        "een kwartslag met de klok mee",
        "20 graden gedraaid, nog binnen het kader",
        "links-rechts gespiegeld",
    ),
    more_title="Dezelfde afbeelding, op andere manieren bemeten en geplaatst",
    more_captions=(
        "natural: eigen grootte, wat het kader ook is",
        "natural, twee keer zo groot, het uitstekende afgesneden",
        "verkleinen om te passen, twee keer zo groot: kleiner gemaakt",
        "verkleinen om te passen, half zo groot: links, in beide richtingen gespiegeld",
        "natural, een kwart zo groot, op de negen ankers",
        "een kwart vanaf links en een kwart naar beneden",
        "een halve slag",
        "boven-onder gespiegeld",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Uma imagem, uma caixa, oito formas de a encaixar",
    captions=(
        "contain: o maior que cabe, com a sua forma",
        "cover: sem vazios, o excesso recortado",
        "stretch: a caixa cheia, a forma perdida",
        "contain, em cima à esquerda, margem de 12 pontos",
        "um quarto de volta para a esquerda",
        "um quarto de volta para a direita",
        "rodada 20 graus, ainda dentro da caixa",
        "espelhada da esquerda para a direita",
    ),
    more_title="A mesma imagem, dimensionada e colocada de outras formas",
    more_captions=(
        "natural: o seu tamanho, seja qual for a caixa",
        "natural, o dobro, o que sobra recortado",
        "reduzir para caber, o dobro: fica mais pequena",
        "reduzir para caber, metade: à esquerda, espelhada nos dois sentidos",
        "natural, um quarto do tamanho, nas nove âncoras",
        "a um quarto da esquerda e um quarto para baixo",
        "meia volta",
        "espelhada de cima para baixo",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Un’immagine, un riquadro, otto modi di adattarla",
    captions=(
        "contain: la più grande che ci sta, forma conservata",
        "cover: nessun vuoto, l’eccesso ritagliato",
        "stretch: il riquadro pieno, la forma persa",
        "contain, in alto a sinistra, margine di 12 punti",
        "un quarto di giro in senso antiorario",
        "un quarto di giro in senso orario",
        "ruotata di 20 gradi, ancora nel suo riquadro",
        "specchiata da sinistra a destra",
    ),
    more_title="La stessa immagine, dimensionata e collocata in altri modi",
    more_captions=(
        "natural: la sua dimensione, qualunque sia il riquadro",
        "natural, il doppio, la parte sporgente ritagliata",
        "riduci per adattare, il doppio: rimpicciolita",
        "riduci per adattare, la metà: a sinistra, specchiata nei due sensi",
        "natural, un quarto della dimensione, sui nove ancoraggi",
        "a un quarto da sinistra e un quarto in basso",
        "mezzo giro",
        "specchiata dall’alto in basso",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Una imagen, una caja, ocho formas de encajarla",
    captions=(
        "contain: lo más grande que cabe, con su forma",
        "cover: sin huecos, lo que sobra recortado",
        "stretch: la caja llena, la forma perdida",
        "contain, arriba a la izquierda, margen de 12 puntos",
        "un cuarto de vuelta a la izquierda",
        "un cuarto de vuelta a la derecha",
        "girada 20 grados, aún dentro de su caja",
        "reflejada de izquierda a derecha",
    ),
    more_title="La misma imagen, dimensionada y colocada de otras formas",
    more_captions=(
        "natural: su propio tamaño, sea cual sea la caja",
        "natural, el doble, lo que sobresale recortado",
        "reducir para caber, el doble: se hace más pequeña",
        "reducir para caber, la mitad: a la izquierda, reflejada en ambos sentidos",
        "natural, un cuarto del tamaño, en los nueve anclajes",
        "a un cuarto desde la izquierda y un cuarto hacia abajo",
        "media vuelta",
        "reflejada de arriba abajo",
    ),
)

# The page in German.
GERMAN = Words(
    title="Ein Bild, ein Rahmen, acht Arten der Einpassung",
    captions=(
        "contain: so groß, wie es passt, die Form bleibt",
        "cover: keine Lücke, der Überstand abgeschnitten",
        "stretch: Rahmen gefüllt, die Form verloren",
        "contain, oben links, 12 Punkt eingerückt",
        "eine Vierteldrehung gegen den Uhrzeigersinn",
        "eine Vierteldrehung im Uhrzeigersinn",
        "um 20 Grad gedreht, noch im Rahmen",
        "von links nach rechts gespiegelt",
    ),
    more_title="Dasselbe Bild, anders bemessen und platziert",
    more_captions=(
        "natural: eigene Größe, unabhängig vom Rahmen",
        "natural, doppelt so groß, Überstand abgeschnitten",
        "shrink to fit, doppelt so groß: verkleinert",
        "shrink to fit, halb so groß: links, doppelt gespiegelt",
        "natural, ein Viertel so groß, an den neun Ankern",
        "ein Viertel von links und ein Viertel von oben",
        "eine halbe Drehung",
        "von oben nach unten gespiegelt",
    ),
)


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


@dataclass(frozen=True)
class Panel:
    """What a panel says it does, the policies it draws the picture by, once each,
    whether what it draws has to be held to the box, and what the picture's size is
    multiplied by before it is fitted."""

    caption: str
    fitted: list[hqf_pdf.FitBox]
    clipped: bool = False
    scale: float = 1.0


def panels(words: Words) -> list[Panel]:
    """The eight policies, in the order they are laid out: the three sizing modes and
    one of them anchored and inset first, then the three turns and the mirror, each
    under the caption `words` gives it."""
    fitted = [
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain), False),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Cover), True),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Stretch), False),
        (
            hqf_pdf.FitBox(
                hqf_pdf.FitMode.Contain,
                anchor=hqf_pdf.Anchor.top_left(),
                margin=12.0,
            ),
            False,
        ),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.left()), False),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.right()), False),
        (
            hqf_pdf.FitBox(
                hqf_pdf.FitMode.Contain,
                turn=hqf_pdf.Turn.angle(math.radians(20.0)),
            ),
            False,
        ),
        (
            hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, mirror=hqf_pdf.Mirror.LeftToRight),
            False,
        ),
    ]
    return [
        Panel(caption, [box], clipped=clipped)
        for (box, clipped), caption in zip(fitted, words.captions)
    ]


# The nine named anchors, bottom row first, each left to right.
ANCHORS = (
    hqf_pdf.Anchor.bottom_left(),
    hqf_pdf.Anchor.bottom(),
    hqf_pdf.Anchor.bottom_right(),
    hqf_pdf.Anchor.left(),
    hqf_pdf.Anchor.center(),
    hqf_pdf.Anchor.right(),
    hqf_pdf.Anchor.top_left(),
    hqf_pdf.Anchor.top(),
    hqf_pdf.Anchor.top_right(),
)


def more_panels(words: Words) -> list[Panel]:
    """The second page's eight policies, in the order they are laid out: the natural
    size, then twice as large and clipped; shrinking to fit twice and half as large;
    the nine anchors; a point between them, upright and not mirrored; the half turn and
    the mirror top to bottom."""
    natural = hqf_pdf.FitMode.Natural
    fitted = [
        ([hqf_pdf.FitBox(natural)], False, 1.0),
        ([hqf_pdf.FitBox(natural)], True, 2.0),
        ([hqf_pdf.FitBox(hqf_pdf.FitMode.ShrinkToFit)], False, 2.0),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.ShrinkToFit, mirror=hqf_pdf.Mirror.Both)],
            False,
            0.5,
        ),
        ([hqf_pdf.FitBox(natural, anchor=anchor) for anchor in ANCHORS], False, 0.25),
        (
            [
                hqf_pdf.FitBox(
                    natural,
                    anchor=hqf_pdf.Anchor.fraction(0.25, 0.75),
                    turn=hqf_pdf.Turn.upright(),
                    mirror=hqf_pdf.Mirror.Neither,
                )
            ],
            False,
            0.5,
        ),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.upside_down())],
            False,
            1.0,
        ),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, mirror=hqf_pdf.Mirror.TopToBottom)],
            False,
            1.0,
        ),
    ]
    return [
        Panel(caption, boxes, clipped=clipped, scale=scale)
        for (boxes, clipped, scale), caption in zip(fitted, words.more_captions)
    ]


def panel_box(index: int) -> tuple[float, float, float, float]:
    """The box the panel at `index` fits into: two to a row, filled left to right."""
    column = index % 2
    row = index // 2
    x = MARGIN + column * (BOX_WIDTH + GAP)
    top = FIRST_ROW - row * ROW_PITCH
    return (x, top - BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT)


def draw_panel(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    image: hqf_pdf.ImageHandle,
    panel: Panel,
    box: tuple[float, float, float, float],
) -> None:
    """Draws one panel: its box's outline, the picture fitted into it, and its
    caption underneath."""
    x, y, width, height = box

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.75))
    content.set_line_width(0.5)
    content.rect(x, y, width, height)
    content.stroke()
    content.restore_state()

    natural = image.size
    size = (natural[0] * panel.scale, natural[1] * panel.scale)
    content.save_state()
    if panel.clipped:
        content.rect(x, y, width, height)
        content.clip()
        content.end_path()
    for fitted in panel.fitted:
        content.save_state()
        content.transform(fitted.matrix(size, box))
        content.draw_image(image, 0.0, 0.0, size[0], size[1])
        content.restore_state()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, 8.5, x, y - CAPTION_DROP, panel.caption)
    content.restore_state()


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.DEFAULT_FONT))
    image = document.add_image(hqf_pdf.Image.from_path(PHOTO))

    drawn = panels(words)
    more = more_panels(words)
    for title, laid in ((words.title, drawn), (words.more_title, more)):
        content = hqf_pdf.Content()
        content.draw_text(font, 16.0, MARGIN, 790.0, title)
        for index, panel in enumerate(laid):
            draw_panel(content, font, image, panel, panel_box(index))

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

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(drawn) + len(more)} panels of one "
        f"{image.width}x{image.height} picture"
    )


if __name__ == "__main__":
    main()