write_filled_in_place.py

The Python file of the “A Form Filled In After It Was Written” example. A form written with its fields empty, then answered the way a program answers a form it received, in a section added to the end of the file: the customer number takes one box of its comb per character, and the PIN shows as dots, its digits kept in the field's value alone.

Python 271 lines

What This Example Is For

A program that receives a form and answers it, a bank opening an account or an insurer completing a claim, must not rewrite the file it was sent: a signature already on it covers its bytes, and a copy kept for the record has to stay what it was. The answers go in as a section added to the end of the file, and everything written before stays where it was.

What This Example Shows

  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
"""Writes a small form, then fills it in as a section added to the file.

The Python twin of the `write_filled_in_place` example in Rust: the same
document, through the binding rather than through the library directly.

The form is written first, its three fields empty. It is then read back and
answered in place, the way a program answers a form it received: the answers and
their appearances are appended to the file as a section of its own, and the bytes
written before stay as they were. The fields are set in Helvetica, one of the fonts
every reader carries, so each answer is drawn into the file and shows in a reader
that draws nothing itself: the name, the customer number set a character to each
box of its comb, and the PIN, drawn as one dot for each of its digits. The digits
are kept in the field's value alone.

The title, the sentence and the labels are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn. The fields' names and the answers are what
a program reads and writes, and stand the same in every language.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


@dataclass(frozen=True)
class Words:
    """The words the page is written in, in one language."""

    # The title at the head of the page.
    title: str
    # The sentence under the title, saying how the answers came in.
    about: str
    # The label beside the name field.
    name: str
    # The label beside the customer number field.
    customer: str
    # The label beside the PIN field.
    pin: str


# The page in English.
ENGLISH = Words(
    title="Account opening",
    about=(
        "The three answers below were filled in after the form was written, as a section "
        "added to the file. The PIN is drawn as dots; its digits are kept in the field's "
        "value alone."
    ),
    name="Full name",
    customer="Customer number",
    pin="PIN",
)

# The page in French.
FRENCH = Words(
    title="Ouverture de compte",
    about=(
        "Le formulaire a d’abord été créé, puis les trois réponses ci-dessous ont été "
        "inscrites dans une section ajoutée à la fin du fichier. Le code secret s’affiche "
        "sous forme de points ; ses chiffres ne figurent que dans la valeur du champ."
    ),
    name="Nom complet",
    customer="Numéro de client",
    pin="Code secret",
)

# The page in German.
GERMAN = Words(
    title="Kontoeröffnung",
    about=(
        "Die drei Antworten unten wurden nach dem Schreiben des Formulars eingetragen, "
        "in einem an die Datei angehängten Abschnitt. Die PIN erscheint als Punkte; ihre "
        "Ziffern stehen nur im Wert des Feldes."
    ),
    name="Vollständiger Name",
    customer="Kundennummer",
    pin="PIN",
)

# The page in Spanish.
SPANISH = Words(
    title="Apertura de cuenta",
    about=(
        "Las tres respuestas de abajo se rellenaron después de escribir el formulario, en "
        "una sección añadida al archivo. El PIN se muestra como puntos; sus cifras solo "
        "constan en el valor del campo."
    ),
    name="Nombre completo",
    customer="Número de cliente",
    pin="PIN",
)

# The page in Italian.
ITALIAN = Words(
    title="Apertura del conto",
    about=(
        "Le tre risposte qui sotto sono state compilate dopo la scrittura del modulo, in "
        "una sezione aggiunta al file. Il PIN appare come punti; le sue cifre si trovano "
        "solo nel valore del campo."
    ),
    name="Nome e cognome",
    customer="Numero cliente",
    pin="Codice PIN",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Abertura de conta",
    about=(
        "As três respostas abaixo foram preenchidas depois de o formulário ter sido "
        "escrito, numa secção acrescentada ao ficheiro. O PIN aparece em pontos; os seus "
        "algarismos ficam apenas no valor do campo."
    ),
    name="Nome completo",
    customer="Número de cliente",
    pin="Código PIN",
)

# The page in Dutch.
DUTCH = Words(
    title="Rekening openen",
    about=(
        "De drie antwoorden hieronder zijn ingevuld nadat het formulier was geschreven, "
        "in een sectie die aan het bestand is toegevoegd. De pincode verschijnt als "
        "puntjes; de cijfers staan alleen in de waarde van het veld."
    ),
    name="Volledige naam",
    customer="Klantnummer",
    pin="Pincode",
)

# 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 answers given to the form, by field name, in the order they are given.
ANSWERS = {"Name": "Ada Lovelace", "Customer": "HQF-0917", "Pin": "4271"}

# How many boxes the customer number's comb is divided into: one to each character of
# the number.
CUSTOMER_BOXES = 8

# What the PIN is drawn as, once for each of its digits.
MASK = "•"

# The size the words and the answers are set at, in points.
SIZE = 11.0
# The size of the title, in points.
TITLE_SIZE = 18.0
# The left edge of the words and of the labels.
X = 72.0
# The left edge of every field.
FIELD_X = 200.0
# The width the sentence under the title is broken to.
TEXT_WIDTH = 450.0
# The colour every field's border is stroked in.
BORDER = hqf_pdf.Rgb.gray(0.6)
# The width every field's border is stroked at, in points.
BORDER_WIDTH = 0.75
# The baseline of the title.
TITLE_TOP = 760.0
# The top of the sentence under the title.
ABOUT_TOP = 735.0
# The baseline of the first label; each one after it stands `ROW` lower.
FIRST_ROW = 650.0
# The room between two labels.
ROW = 36.0


def form_page(
    font: hqf_pdf.FontHandle, helvetica: hqf_pdf.FontHandle, words: Words
) -> hqf_pdf.Page:
    """The form: a title, the sentence under it, and three labelled fields, empty."""
    content = hqf_pdf.Content()
    page = hqf_pdf.Page.a4()

    content.draw_text(font, TITLE_SIZE, X, TITLE_TOP, words.title)
    about = hqf_pdf.TextFlow(font, SIZE, leading=SIZE * 1.4)
    lines = about.break_lines(words.about, TEXT_WIDTH)
    about.draw(content, lines, X, ABOUT_TOP, TEXT_WIDTH)

    def field(name: str, row: float, width: float, **settings) -> hqf_pdf.TextField:
        return hqf_pdf.TextField(
            name,
            FIELD_X,
            row - 4.0,
            width,
            SIZE + 8.0,
            helvetica,
            SIZE,
            border_color=BORDER,
            border_width=BORDER_WIDTH,
            **settings,
        )

    name_row = FIRST_ROW
    content.draw_text(font, SIZE, X, name_row, words.name)
    page.add_field(field("Name", name_row, 240.0, tooltip=words.name))

    customer_row = FIRST_ROW - ROW
    content.draw_text(font, SIZE, X, customer_row, words.customer)
    page.add_field(
        field(
            "Customer",
            customer_row,
            160.0,
            comb=True,
            max_length=CUSTOMER_BOXES,
            tooltip=words.customer,
        )
    )

    pin_row = FIRST_ROW - 2.0 * ROW
    content.draw_text(font, SIZE, X, pin_row, words.pin)
    page.add_field(field("Pin", pin_row, 80.0, password=True, tooltip=words.pin))

    page.set_content(content)
    return page


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    helvetica = document.add_standard_font(hqf_pdf.StandardFont.helvetica())
    document.add_page(form_page(font, helvetica, words))
    written = document.to_bytes()

    # The form read back and answered in place: the answers and the appearances drawn
    # for them are appended to the file as a section of their own.
    update = hqf_pdf.IncrementalUpdate(written)
    update.set_license(_licence.licensed())
    update.set_baking(hqf_pdf.FillBaking(password_mask=MASK))
    filled = update.to_filled_bytes(ANSWERS)

    Path(out).write_bytes(filled)
    print(
        f"wrote {out}: {len(filled)} bytes, the form's own {len(written)} and "
        f"{len(filled) - len(written)} added by the answers"
    )


if __name__ == "__main__":
    main()