write_pdfa1b.py

Le fichier Python de l’exemple « Certificat de travail en PDF/A-1b ». Un certificat conforme à la première partie de la norme d’archivage, la plus stricte : PDF 1.4, un contenu entièrement opaque et toujours affiché, sans pièce jointe.

Python 400 lignes

À quoi sert cet exemple

Un dépositaire ou un registre qui a fixé ses règles il y a des années peut encore exiger nommément la première partie de la norme d’archivage. Un document envoyé dans une partie plus récente revient refusé, si bien rédigé soit-il, et il faut le recréer.

Ce que montre cet exemple

  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
"""Writes a certificate of employment claiming the first part of the archival
standard, at level B.

The first part is the strict one. It is built on PDF 1.4, and it closes what
the later editions let back in: nothing on the page is painted so that what
lies behind it shows through, no layer can be switched off, and no file
travels inside the document. What is left is a sheet that draws itself out
of what it carries, which is what the standard asked for in 2005.

Level B promises the look of the page and nothing more. Level A, which adds
the tree saying what the page is made of, is `write_pdfa1a`.

Whether the result really is PDF/A-1B is not for us to say. `veraPDF` says,
and `scripts/check_pdfa.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_pdfa1b.py [out.pdf] [font.ttf]`
       `HQF_PDF_LANG=fr python examples/write_pdfa1b.py`
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# When the certificate 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-02-04T09:15:00+01: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 certificate 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
    # The line under the heading saying what the record is filed under.
    reference: str
    # What the page says of the part it claims, in two runs set end to end with a space
    # between them.
    body: tuple[str, str]
    # What each line of the record asks, one a line.
    labels: str
    # What each line of the record answers, beside its label.
    answers: str
    # The line under the record, saying who signed it.
    signed: str


# The certificate in English.
ENGLISH = Words(
    title="Certificate of employment, 4 February 2026",
    subject="A record an archive keeps under the first edition of the standard",
    heading="Certificate of employment",
    reference="Reference 2026-0184, issued 4 February 2026",
    body=(
        (
            "This sheet claims the first part of the archival standard, at the level "
            "that promises the look of the page and nothing else. Every face it draws "
            "with is carried inside the file, every colour says what it means, and "
            "nothing on the page waits on a program, a network or a font that happens "
            "to be installed."
        ),
        (
            "The first part is also the strictest: nothing here is painted so that "
            "what lies behind it shows through, no part of the page can be switched "
            "off, and no file travels inside the document. A record that needs any of "
            "those claims a later part instead."
        ),
    ),
    labels="Employee\nPosition\nEmployed since\nHours",
    answers=(
        "Camille Marchand\nHead of the drawing office\n3 September 2018\nFull time, 35 "
        "hours a week"
    ),
    signed="Signed at Cabriès, for HQF Development.",
)


# The certificate in French.
FRENCH = Words(
    title="Attestation d’emploi, 4 février 2026",
    subject=("Un document que conserve un service d’archives selon la première édition"
             " de la norme"),
    heading="Attestation d’emploi",
    reference="Référence 2026-0184, délivrée le 4 février 2026",
    body=(
        (
            ("Cette feuille déclare suivre la première partie de la norme d’archivage,"
             " au niveau qui promet l’apparence de la page et rien d’autre. Chaque "
             "police employée est incorporée au fichier, chaque couleur dit ce qu’elle"
             " signifie, et rien sur la page ne dépend d’un programme, d’un réseau ou "
             "d’une police installée par hasard.")
        ),
        (
            ("La première partie est aussi la plus stricte : rien n’y est peint de "
             "façon à laisser voir ce qui se trouve derrière, aucun élément de la page"
             " ne peut être masqué et aucun fichier ne voyage dans le document. Un "
             "document qui a besoin de l’une de ces choses se réclame d’une partie "
             "ultérieure.")
        ),
    ),
    labels="Nom\nFonction\nDate d’embauche\nTemps de travail",
    answers=(
        "Camille Marchand\nResponsable du bureau d’études\n3 septembre 2018\nTemps "
        "plein, 35 heures par semaine"
    ),
    signed="Fait à Cabriès, pour HQF Development.",
)


# The certificate in German.
GERMAN = Words(
    title="Beschäftigungsnachweis, 4. Februar 2026",
    subject="Ein Dokument, das ein Archiv nach dem ersten Teil der Norm aufbewahrt",
    heading="Beschäftigungsnachweis",
    reference="Aktenzeichen 2026-0184, ausgestellt am 4. Februar 2026",
    body=(
        (
            ("Dieses Blatt erklärt Konformität mit dem ersten Teil der Archivnorm, auf"
             " der Stufe, die das Aussehen der Seite zusagt und sonst nichts. Jede "
             "verwendete Schrift steckt in der Datei, jede Farbe gibt an, was sie "
             "bedeutet, und nichts auf der Seite wartet auf ein Programm, ein Netzwerk"
             " oder eine zufällig installierte Schrift.")
        ),
        (
            ("Der erste Teil ist auch der strengste: Nichts ist hier so aufgetragen, "
             "dass Dahinterliegendes durchscheint, kein Teil der Seite lässt sich "
             "ausblenden, und keine Datei reist im Dokument mit. Ein Dokument, das "
             "etwas davon braucht, erklärt stattdessen Konformität mit einem späteren "
             "Teil.")
        ),
    ),
    labels="Name\nTätigkeit\nBeschäftigt seit\nArbeitszeit",
    answers=(
        "Camille Marchand\nLeitung des Konstruktionsbüros\n3. September "
        "2018\nVollzeit, 35 Stunden pro Woche"
    ),
    signed="Unterzeichnet in Cabriès für HQF Development.",
)


# The certificate in Spanish.
SPANISH = Words(
    title="Certificado laboral, 4 de febrero de 2026",
    subject="Un documento que un archivo conserva según la primera edición de la norma",
    heading="Certificado laboral",
    reference="Referencia 2026-0184, expedido el 4 de febrero de 2026",
    body=(
        (
            ("Esta hoja declara cumplir la primera parte de la norma de archivo, en el"
             " nivel que promete el aspecto de la página y nada más. Cada fuente que "
             "usa va dentro del fichero, cada color dice lo que significa y nada en la"
             " página depende de un programa, de una red ni de una fuente instalada en"
             " el equipo.")
        ),
        (
            "La primera parte es también la más estricta: aquí nada se pinta de modo "
            "que se vea lo que hay detrás, ninguna parte de la página puede ocultarse "
            "y ningún fichero viaja dentro del documento. Un documento que necesite "
            "algo de eso declara una parte posterior."
        ),
    ),
    labels="Nombre\nCargo\nEn plantilla desde\nJornada",
    answers=(
        "Camille Marchand\nResponsable de la oficina técnica\n3 de septiembre de "
        "2018\nCompleta, 35 horas semanales"
    ),
    signed="Firmado en Cabriès, en nombre de HQF Development.",
)


# The certificate in Italian.
ITALIAN = Words(
    title="Certificato di servizio, 4 febbraio 2026",
    subject=(
        "Un documento che un archivio conserva secondo la prima edizione della norma"
    ),
    heading="Certificato di servizio",
    reference="Riferimento 2026-0184, rilasciato il 4 febbraio 2026",
    body=(
        (
            "Questo foglio dichiara di rispettare la prima parte della norma di "
            "archiviazione, al livello che promette l’aspetto della pagina e "
            "nient’altro. Ogni carattere che usa è contenuto nel file, ogni colore "
            "dice che cosa significa e nulla sulla pagina dipende da un programma, da "
            "una rete o da un font che si trovi installato."
        ),
        (
            "La prima parte è anche la più severa: qui nulla è dipinto in modo da "
            "lasciar vedere ciò che sta dietro, nessuna parte della pagina può essere "
            "nascosta e nessun file viaggia nel documento. Un documento che ha bisogno "
            "di una di queste cose dichiara una parte successiva."
        ),
    ),
    labels="Dipendente\nMansione\nIn servizio dal\nOrario",
    answers=(
        "Camille Marchand\nResponsabile dell’ufficio tecnico\n3 settembre 2018\nTempo "
        "pieno, 35 ore settimanali"
    ),
    signed="Firmato a Cabriès, per HQF Development.",
)


# The certificate in Portuguese.
PORTUGUESE = Words(
    title="Declaração de trabalho, 4 de fevereiro de 2026",
    subject="Um documento que um arquivo guarda segundo a primeira edição da norma",
    heading="Declaração de trabalho",
    reference="Referência 2026-0184, emitida a 4 de fevereiro de 2026",
    body=(
        (
            "Esta folha declara cumprir a primeira parte da norma de arquivo, no nível "
            "que promete o aspeto da página e nada mais. Cada tipo de letra que usa "
            "está dentro do ficheiro, cada cor diz o que significa e nada na página "
            "depende de um programa, de uma rede ou de um tipo de letra que por acaso "
            "esteja instalado."
        ),
        (
            "A primeira parte é também a mais rigorosa: nada aqui é pintado de forma a "
            "deixar ver o que está por trás, nenhuma parte da página pode ser ocultada "
            "e nenhum ficheiro viaja dentro do documento. Um documento que precise de "
            "alguma destas coisas declara uma parte posterior."
        ),
    ),
    labels="Nome\nFunção\nAo serviço desde\nHorário",
    answers=(
        "Camille Marchand\nResponsável pelo gabinete de projeto\n3 de setembro de "
        "2018\nTempo inteiro, 35 horas por semana"
    ),
    signed="Assinado em Cabriès, pela HQF Development.",
)


# The certificate in Dutch.
DUTCH = Words(
    title="Werkgeversverklaring, 4 februari 2026",
    subject="Een document dat een archief bewaart volgens de eerste editie van de norm",
    heading="Werkgeversverklaring",
    reference="Kenmerk 2026-0184, afgegeven op 4 februari 2026",
    body=(
        (
            ("Dit blad verklaart te voldoen aan het eerste deel van de archiefnorm, op"
             " het niveau dat het uiterlijk van de pagina belooft en verder niets. Elk"
             " lettertype dat het gebruikt, zit in het bestand, elke kleur zegt wat ze"
             " betekent, en niets op de pagina wacht op een programma, een netwerk of "
             "een lettertype dat toevallig geïnstalleerd is.")
        ),
        (
            (("Het eerste deel is ook het strengste: niets is hier zo aangebracht dat "
              "wat erachter ligt doorschemert, geen deel van de pagina kan worden "
              "uitgeschakeld en geen bestand reist mee in het document. Een document "
              "dat iets daarvan nodig heeft, verklaart te voldoen aan een later deel."))
        ),
    ),
    labels="Werknemer\nFunctie\nIn dienst sinds\nArbeidsduur",
    answers=(
        ("Camille Marchand\nHoofd van het tekenbureau\n3 september 2018\nVoltijd, 35 "
         "uur per week")
    ),
    signed="Ondertekend te Cabriès, namens HQF Development.",
)

# 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.reference,
        "size": 10.5,
        "left": 72.0,
        "top": 750.0,
        "width": 451.0,
        "set": None,
    },
    {
        "text": lambda words: " ".join(words.body),
        "size": 11.0,
        "left": 72.0,
        "top": 716.0,
        "width": 451.0,
        "set": (16.0, hqf_pdf.Align.Justify),
    },
    {
        "text": lambda words: words.labels,
        "size": 11.0,
        "left": 72.0,
        "top": 580.0,
        "width": 451.0,
        "set": (17.0, hqf_pdf.Align.Left),
    },
    {
        "text": lambda words: words.answers,
        "size": 11.0,
        "left": 200.0,
        "top": 580.0,
        "width": 323.0,
        "set": (17.0, hqf_pdf.Align.Left),
    },
    {
        "text": lambda words: words.signed,
        "size": 11.0,
        "left": 72.0,
        "top": 480.0,
        "width": 451.0,
        "set": None,
    },
)


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_version(hqf_pdf.Version.V1_4)
    document.set_conformance(hqf_pdf.PdfA.A1B)
    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()