write_pdfa4.py

Die Python-Datei des Beispiels „Beförderungsbedingungen in PDF/A-4 auf Basis von PDF 2.0“. Beförderungsbedingungen nach dem vierten Teil der Archivnorm, der auf PDF 2.0 aufbaut und die Stufen A, B und U der früheren Teile abschafft.

Python 312 Zeilen

Wofür dieses Beispiel da ist

Der vierte Teil der Archivnorm ist der, an den sich Archive halten, seit es eine zweite Version von PDF gibt. Er schafft die Stufen A, B und U der früheren Teile ab: Ein Dokument erfüllt den Teil oder nicht, und nur zwei Varianten ergänzen ihn, F für angehängte Dateien beliebiger Art und E für technische Zeichnungen. Eine Datei, die noch auf einer älteren PDF-Version beruht, kann ihn gar nicht erfüllen.

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
"""Writes terms of carriage claiming the fourth part of the archival standard.

The fourth part is built on the second version of PDF, and it drops the
levels the earlier parts carry: there is one part and no letter after it.
Every face is carried whole inside the file and every colour says what it
means, as in every part before it.

Whether the result really is PDF/A-4 is not for us to say. `veraPDF` says,
and `scripts/check_archival.sh` asks it.

The words of the page and of its metadata are held in `Words`, once per language,
and `HQF_PDF_LANG` picks which set the record is written in.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# When the record was drawn up. The library never reads the clock — a document that
# stamped itself with the time would be a different file on every build — so the caller
# says when.
ISSUED = "2026-05-04T09:00:00+02:00"

# Who the file says wrote it, and what produced it, in every language alike.
AUTHOR = "HQF Development"
PRODUCER = "hqf-pdf-server"

@dataclass(frozen=True)
class Words:
    """Every word the terms is written in, in one language."""

    # What the file says it is, in its metadata.
    title: str
    # What the file says it is about, in its metadata.
    subject: str
    # The heading at the top of the page.
    heading: str
    # What the page says of the part it claims.
    body: str
    # The terms themselves, one a line.
    terms: str


# The terms in English.
ENGLISH = Words(
    title="Terms of carriage, edition of 2026",
    subject="A record written on the version of PDF the fourth part is built on",
    heading="Terms of carriage, edition of 2026",
    body=(
        "This record claims the fourth part of the archival standard, the one built on "
        "the second version of PDF. It says what it is in its metadata packet and "
        "nowhere else: there is no information dictionary behind the page, and the "
        "title above is the title the file carries. Everything the part asks for is "
        "here and nothing more: every face is carried whole inside the file, every "
        "colour says what it means, and the pages keep their looks with no font, no "
        "profile and no program to fetch from anywhere."
    ),
    terms=(
        "Goods are carried under the schedule current on the day they are accepted.\nA "
        "schedule that changes after acceptance does not reach an order already "
        "accepted."
    ),
)


# The terms in French.
FRENCH = Words(
    title="Conditions de transport, édition 2026",
    subject=("Un document bâti sur la version de PDF sur laquelle repose la quatrième "
             "partie"),
    heading="Conditions de transport, édition 2026",
    body=(
        ("Ce document déclare suivre la quatrième partie de la norme d’archivage, "
         "celle qui repose sur la deuxième version de PDF. Il dit ce qu’il est dans "
         "son paquet de métadonnées et nulle part ailleurs : aucun dictionnaire "
         "d’informations derrière la page, et le titre ci-dessus est le titre même du "
         "fichier. Tout ce que la partie exige est là, et rien de plus : chaque police"
         " est incorporée en entier au fichier, chaque couleur dit ce qu’elle "
         "signifie, et les pages gardent leur apparence sans police, profil ni "
         "programme à aller chercher où que ce soit.")
    ),
    terms=(
        ("Les marchandises sont transportées au barème en vigueur le jour de leur "
         "prise en charge.\nUn barème modifié après la prise en charge ne s’applique "
         "pas à une commande déjà prise en charge.")
    ),
)


# The terms in German.
GERMAN = Words(
    title="Beförderungsbedingungen, Ausgabe 2026",
    subject="Ein Dokument in der PDF-Version, auf der der vierte Teil aufbaut",
    heading="Beförderungsbedingungen, Ausgabe 2026",
    body=(
        ("Dieses Dokument erklärt Konformität mit dem vierten Teil der Archivnorm, der"
         " auf der zweiten PDF-Version aufbaut. Was es ist, gibt es in seinem "
         "Metadatenpaket an und nirgends sonst: Hinter der Seite steht kein "
         "Informationswörterbuch, und der Titel oben ist der Titel der Datei. Alles, "
         "was der Teil verlangt, ist vorhanden, und nichts darüber hinaus: Jede "
         "Schrift steckt vollständig in der Datei, jede Farbe gibt an, was sie "
         "bedeutet, und die Seiten behalten ihr Aussehen, ohne dass eine Schrift, ein "
         "Profil oder ein Programm von irgendwoher geholt werden muss.")
    ),
    terms=(
        "Waren werden nach dem Tarif befördert, der am Tag ihrer Annahme gilt.\nEin "
        "Tarif, der sich nach der Annahme ändert, betrifft keinen bereits angenommenen "
        "Auftrag."
    ),
)


# The terms in Spanish.
SPANISH = Words(
    title="Condiciones de transporte, edición de 2026",
    subject=(
        "Un documento escrito en la versión de PDF en la que se basa la cuarta parte"
    ),
    heading="Condiciones de transporte, edición de 2026",
    body=(
        ("Este documento declara cumplir la cuarta parte de la norma de archivo, la "
         "que se basa en la segunda versión de PDF. Dice lo que es en su paquete de "
         "metadatos y en ningún otro sitio: no hay diccionario de información detrás "
         "de la página, y el título de arriba es el título del fichero. Aquí está todo"
         " lo que la parte exige y nada más: cada fuente va entera dentro del fichero,"
         " cada color dice lo que significa y las páginas conservan su aspecto sin "
         "fuentes, perfiles ni programas que ir a buscar a ninguna parte.")
    ),
    terms=(
        ("La mercancía viaja según la tarifa vigente el día en que se acepta.\nUn "
         "cambio de tarifa posterior a la aceptación no afecta a los pedidos ya "
         "aceptados.")
    ),
)


# The terms in Italian.
ITALIAN = Words(
    title="Condizioni di trasporto, edizione 2026",
    subject="Un documento scritto sulla versione di PDF su cui poggia la quarta parte",
    heading="Condizioni di trasporto, edizione 2026",
    body=(
        ("Questo documento dichiara di rispettare la quarta parte della norma di "
         "archiviazione, quella costruita sulla seconda versione di PDF. Dice che "
         "cos’è nel suo pacchetto di metadati e in nessun altro punto: dietro la "
         "pagina non c’è alcun dizionario delle informazioni, e il titolo qui sopra è "
         "il titolo del file. Tutto ciò che la parte chiede c’è, e niente di più: ogni"
         " carattere è contenuto per intero nel file, ogni colore dice che cosa "
         "significa e le pagine conservano il loro aspetto senza font, profili o "
         "programmi da andare a prendere altrove.")
    ),
    terms=(
        ("La merce viaggia secondo il tariffario in vigore il giorno in cui è "
         "accettata.\nUn tariffario cambiato dopo l’accettazione non tocca un ordine "
         "già accettato.")
    ),
)


# The terms in Portuguese.
PORTUGUESE = Words(
    title="Condições de transporte, edição de 2026",
    subject="Um documento escrito na versão do PDF em que assenta a quarta parte",
    heading="Condições de transporte, edição de 2026",
    body=(
        "Este documento declara cumprir a quarta parte da norma de arquivo, a que "
        "assenta na segunda versão do PDF. Diz o que é no seu pacote de metadados e em "
        "mais lado nenhum: não há dicionário de informação por trás da página, e o "
        "título acima é o título do ficheiro. Está aqui tudo o que a parte exige e "
        "nada mais: cada tipo de letra está inteiro dentro do ficheiro, cada cor diz o "
        "que significa e as páginas mantêm o seu aspeto sem tipos de letra, perfis ou "
        "programas a ir buscar a lado nenhum."
    ),
    terms=(
        "A mercadoria é transportada segundo a tabela em vigor no dia em que é "
        "aceite.\nUma tabela alterada após a aceitação não abrange uma encomenda já "
        "aceite."
    ),
)


# The terms in Dutch.
DUTCH = Words(
    title="Vervoersvoorwaarden, editie 2026",
    subject="Een document op de PDF-versie waarop het vierde deel gebaseerd is",
    heading="Vervoersvoorwaarden, editie 2026",
    body=(
        ("Dit document verklaart te voldoen aan het vierde deel van de archiefnorm, "
         "het deel dat op de tweede versie van PDF gebaseerd is. Het zegt wat het is "
         "in zijn metadatapakket en nergens anders: achter de pagina staat geen "
         "informatiewoordenboek, en de titel hierboven is de titel van het bestand. "
         "Alles wat het deel vereist, is aanwezig, en niets meer: elk lettertype zit "
         "volledig in het bestand, elke kleur zegt wat ze betekent, en de pagina’s "
         "behouden hun uiterlijk zonder lettertype, profiel of programma dat ergens "
         "vandaan moet komen.")
    ),
    terms=(
        ("Goederen worden vervoerd volgens het tarief dat geldt op de dag van "
         "aanvaarding.\nEen tarief dat na aanvaarding wijzigt, raakt geen bestelling "
         "die al aanvaard is.")
    ),
)

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


# The blocks of words the page carries, in the order it draws them: the box each goes
# in, the size it is set at, and the leading and alignment where it states them. A block
# the request states in several runs is one run of words here.
BLOCKS = (
    {
        "text": lambda words: words.heading,
        "size": 20.0,
        "left": 72.0,
        "top": 782.0,
        "width": 451.0,
        "set": None,
    },
    {
        "text": lambda words: words.body,
        "size": 11.0,
        "left": 72.0,
        "top": 736.0,
        "width": 451.0,
        "set": (16.0, hqf_pdf.Align.Justify),
    },
    {
        "text": lambda words: words.terms,
        "size": 11.0,
        "left": 72.0,
        "top": 596.0,
        "width": 451.0,
        "set": (17.0, hqf_pdf.Align.Left),
    },
)


def sheet(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Page:
    """The one page, block by block."""
    content = hqf_pdf.Content()
    for block in BLOCKS:
        settings = {}
        if block["set"] is not None:
            leading, align = block["set"]
            settings = {"leading": leading, "align": align}
        flow = hqf_pdf.TextFlow(handle, block["size"], **settings)
        lines = flow.break_lines(block["text"](words), block["width"])
        # The Python side opens and closes the text object itself, where the Rust side
        # leaves that to the caller.
        flow.draw(content, lines, block["left"], block["top"], block["width"])

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page


def main() -> None:
    """Writes the file, and says where it went."""
    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
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("pdfa4.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    # The fourth part is built on the second version of PDF, and the standard refuses a
    # file that declares an earlier one.
    document.set_version(hqf_pdf.Version.V2_0)
    document.set_conformance(hqf_pdf.PdfA.A4)
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.title,
            author=AUTHOR,
            subject=words.subject,
            producer=PRODUCER,
            created=ISSUED,
        )
    )

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    document.add_page(sheet(handle, words))

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


if __name__ == "__main__":
    main()