Changer de style au milieu d'un paragraphe

Un paragraphe dont le style change en cours de route : la taille, le soulignement, la couleur.

Python write_rich_text.py 193 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
"""Sets paragraphs whose style changes inside them: sizes that shift mid-line, a
total that is underlined, and a word that turns underlined halfway through.

The Python twin of the `write_rich_text` example in Rust. Each block is laid out in
the same box, so a line is as tall as the tallest style standing on it, and an
underline is drawn where each font says one goes.

The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set is set. Each is cut around the run whose style changes, so that a language says
what it has to say around the same three pieces.

Usage: python examples/write_rich_text.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_rich_text.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 of every box, the width they are broken to, the top of the first one,
# and the gap between one block and the next.
LEFT = 56.0
WIDTH = 420.0
TOP = 760.0
GAP = 26.0

# The sum the first paragraph is about. A total is not language.
AMOUNT = "1 240.00 EUR"


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

    Every paragraph is cut around the run that carries the style being shown, so the
    piece that is underlined, enlarged or coloured is a piece of the sentence rather
    than a sentence of its own.
    """

    # The line at the head of the page.
    title: str
    # The first paragraph, cut around the amount it names.
    due: tuple[str, str]
    # The second, cut around the run set in the largest type.
    tallest: tuple[str, str, str]
    # The third, cut around the run that carries its own colour.
    coloured: tuple[str, str, str]
    # The fourth, cut in the middle of a word: the second piece turns underlined without
    # the word being broken at the join.
    joined: tuple[str, str, str]
    # The fifth, cut around the run named by the alignment it is set to.
    small: tuple[str, str, str]


# The page in English.
ENGLISH = Words(
    title="Rich text: styles, sizes, underlining, colour",
    due=(
        "The amount due is ",
        ", payable within thirty days. The balance carries interest at the "
        "statutory rate from the day it falls due, and no reminder has to be "
        "sent for it to do so.",
    ),
    tallest=(
        "A line is as tall as ",
        "the largest",
        " of the styles standing on it, and no taller.",
    ),
    coloured=(
        "A run can carry its own ",
        "colour",
        ", set apart from the black around it.",
    ),
    joined=(
        "A word may change style in the middle: under",
        "lined",
        " is still one word, and is never broken at the join.",
    ),
    small=(
        "The small print sits in small type, ",
        "flush right",
        ", below the body of the text.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Texte enrichi : styles, tailles, soulignement, couleur",
    due=(
        "Le montant dû est de ",
        ", payable sous trente jours. Le solde porte intérêt au taux légal à "
        "compter du jour de son échéance, sans qu'aucun rappel n'ait à être "
        "envoyé.",
    ),
    tallest=(
        "Une ligne est aussi haute que ",
        "le plus grand",
        " des styles qui s'y tiennent, et pas davantage.",
    ),
    coloured=(
        "Un passage peut porter sa propre ",
        "couleur",
        ", distincte du noir qui l'entoure.",
    ),
    joined=(
        "Un mot peut changer de style en son milieu : souli",
        "gné",
        " reste un seul mot, et n'est jamais coupé à la jointure.",
    ),
    small=(
        "Les mentions légales sont en petits caractères, ",
        "alignées à droite",
        ", sous le corps du texte.",
    ),
)


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


def blocks(font: hqf_pdf.FontHandle, words: Words) -> list[hqf_pdf.RichText]:
    """The paragraphs, in the order they are shown."""
    regular = hqf_pdf.Style(font, 11.0)
    small = hqf_pdf.Style(font, 8.0)
    large = hqf_pdf.Style(font, 17.0)
    marked = hqf_pdf.Style(font, 11.0, underline=True)
    accent = hqf_pdf.Style(font, 11.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))

    return [
        hqf_pdf.RichText(align=hqf_pdf.Align.Justify)
        .push(words.due[0], regular)
        .push(AMOUNT, marked)
        .push(words.due[1], regular),
        hqf_pdf.RichText()
        .push(words.tallest[0], regular)
        .push(words.tallest[1], large)
        .push(words.tallest[2], regular),
        hqf_pdf.RichText()
        .push(words.coloured[0], regular)
        .push(words.coloured[1], accent)
        .push(words.coloured[2], regular),
        hqf_pdf.RichText()
        .push(words.joined[0], regular)
        .push(words.joined[1], marked)
        .push(words.joined[2], regular),
        hqf_pdf.RichText(align=hqf_pdf.Align.Right)
        .push(words.small[0], small)
        .push(words.small[1], small)
        .push(words.small[2], small),
    ]


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

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

    content = hqf_pdf.Content()
    content.draw_text(font, 14.0, LEFT, TOP + 24.0, words.title)

    paragraphs = blocks(font, words)
    top = TOP
    for block in paragraphs:
        lines = block.break_lines(WIDTH)
        block.draw(content, lines, LEFT, top, WIDTH)
        top -= hqf_pdf.RichText.height(lines) + GAP

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

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


if __name__ == "__main__":
    main()