A commercial invoice

A commercial invoice: letterhead, logo, a billed-lines table, totals, and a QR code that pays it by SEPA transfer.

Python write_invoice.py 524 lines
  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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
"""Draws a commercial invoice: a letterhead, a billed-lines table, totals, and a
payment block whose amount can be paid by scanning a code.

The Python twin of the `write_invoice` example in Rust. It puts a logo, styled
text, a paginating table, and a QR code on one page, and the code it draws is a
SEPA credit transfer: a phone's banking app reads it and offers to pay the exact
amount to the exact account, so a person never types an IBAN by hand.

Whether that code pays is not for the page to say, and not for an eye: a scanner
says. `scripts/check_qr.sh` points a decoder at the rendered page and reads back
the transfer.

Every word the page draws is held in `Words`, once per language, and
`HQF_PDF_LANG` picks which one is drawn. Figures, dates in the file's own name,
the account number and the invoice's number are the same in both.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# A4, in points, and the page's left edge with its mirrored right.
PAGE_WIDTH = 595.276
PAGE_HEIGHT = 841.89
LEFT = 56.0
RIGHT = PAGE_WIDTH - LEFT
TABLE_WIDTH = PAGE_WIDTH - 2 * LEFT

# The ink the headings and rules are drawn in, and the grey of the small print.
ACCENT = hqf_pdf.Rgb(0.11, 0.33, 0.55)
MUTED = hqf_pdf.Rgb(0.42, 0.42, 0.45)
INK = hqf_pdf.Rgb(0.1, 0.1, 0.12)

# The logo the letterhead carries: the committed fixture, so the example runs on any
# machine. It stands in for the seller's mark.
LOGO = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images" / "hqf_development.png"


@dataclass(frozen=True)
class Item:
    """What one line of the invoice sells, apart from what it is called: the figures
    read the same whatever language the page is set in.
    """

    quantity: int
    unit_price: float


# The lines this invoice bills, in the order ``Words.items`` names them.
ITEMS = [Item(14, 620.0), Item(6, 480.0), Item(1, 1440.0), Item(2, 950.0)]

# The rate the invoice charges tax at.
VAT_RATE = 0.2

# What the invoice is called.
NUMBER = "2026-0142"

# The seller, and the numbers a French invoice has to carry.
SELLER = "HQF Development"
SELLER_ADDRESS = "42 lot les Genêts, 13480 Calas, France"
SELLER_SITE = "www.hqf.fr"
SELLER_SIRET = "SIRET 752 492 777 00012"
SELLER_APE = "APE 6202A"
SELLER_VAT = "FR59 752 492 777"

# Who the invoice is billed to.
BUYER = "Northwind Trading SARL"
BUYER_STREET = "18 quai du Port"
BUYER_CITY = "13002 Marseille, France"

# The account the QR code pays into, ungrouped as the standard wants it, and grouped as
# the page shows it. The number is a documentation IBAN, not a live account: what the
# example demonstrates is the transfer, not the destination.
IBAN = "FR1420041010050500013M02606"
IBAN_SHOWN = "FR14 2004 1010 0505 0001 3M02 606"


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

    What is not language stays out of it: the figures, the account number, the invoice's
    number and the seller's and buyer's names and addresses are drawn from constants of
    their own and read the same in every language.
    """

    # The word the payment reference and the document's title are built from, and the
    # word set large at the head of the page.
    invoice: str
    heading: str
    # What stands before the invoice's number.
    number_label: str
    # What stands before each date, and that date as this language writes it.
    issue_label: str
    issue_date: str
    due_label: str
    due_date: str
    # The short form of the due date's label, set under the amount owed.
    due_short: str
    # The heading over the buyer, and the heading over what is owed.
    bill_to: str
    amount_due: str
    # What each billed line is called, in the order ``ITEMS`` bills them.
    items: tuple[str, str, str, str]
    # The four column headings of the table.
    description: str
    quantity: str
    unit_price: str
    amount: str
    # The three totals under the billed lines.
    subtotal: str
    tax: str
    total: str
    # The heading over the payment block.
    payment: str
    # The sentence the payment block sets, cut where the amount and the invoice's number
    # go into it.
    terms_before: str
    terms_around_number: str
    terms_after: str
    # What stands before the account number, and what stands under the code.
    iban_label: str
    caption: str
    # The word before the seller's tax number in the footer.
    vat: str


# The invoice in English.
ENGLISH = Words(
    invoice="Invoice",
    heading="INVOICE",
    number_label="Invoice No.",
    issue_label="Issue date",
    issue_date="19 July 2026",
    due_label="Due date",
    due_date="18 August 2026",
    due_short="Due",
    bill_to="BILL TO",
    amount_due="AMOUNT DUE",
    items=(
        "Web application development",
        "UX and graphic design",
        "Managed hosting — annual plan",
        "On-site training (Django, per day)",
    ),
    description="Description",
    quantity="Qty",
    unit_price="Unit price",
    amount="Amount",
    subtotal="Subtotal",
    tax="VAT at 20 %",
    total="Total due",
    payment="PAYMENT",
    terms_before="Please transfer ",
    terms_around_number=" within 30 days, quoting invoice ",
    terms_after=". Scan the code to pay the exact amount to the account below.",
    iban_label="IBAN",
    caption="Scan to pay — SEPA",
    vat="VAT",
)

# The invoice in French.
FRENCH = Words(
    invoice="Facture",
    heading="FACTURE",
    number_label="Facture n°",
    issue_label="Date d'émission",
    issue_date="19 juillet 2026",
    due_label="Échéance",
    due_date="18 août 2026",
    due_short="Échéance",
    bill_to="FACTURÉ À",
    amount_due="MONTANT DÛ",
    items=(
        "Développement d'application web",
        "Conception graphique et UX",
        "Hébergement infogéré — forfait annuel",
        "Formation sur site (Django, par jour)",
    ),
    description="Désignation",
    quantity="Qté",
    unit_price="Prix unitaire",
    amount="Montant",
    subtotal="Total HT",
    tax="TVA 20 %",
    total="Total TTC",
    payment="PAIEMENT",
    terms_before="Payable par virement de ",
    terms_around_number=" sous 30 jours. Merci de rappeler le numéro de facture ",
    terms_after=". Scannez le code pour payer le montant exact sur le compte ci-dessous.",
    iban_label="IBAN",
    caption="Scannez pour payer — SEPA",
    vat="TVA",
)


# 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 amount(value: float) -> str:
    """An amount, as an invoice writes it: "4 250.00 EUR"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = ""
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{grouped}.{hundredths} EUR"


def sepa_transfer(words: Words, total: float) -> str:
    """The line the QR code carries: a SEPA credit transfer in the EPC069-12 format,
    the one a banking app reads to offer a transfer of ``total`` to the seller. The
    BIC line is left empty, which the standard allows for an account reachable in the
    single euro payments area, and the reference travels as free text, in the language
    the page is set in.
    """
    return "\n".join(
        [
            "BCD",
            "002",
            "1",
            "SCT",
            "",
            SELLER,
            IBAN,
            f"EUR{total:.2f}",
            "",
            "",
            f"{words.invoice} {NUMBER}",
        ]
    )


def text(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    x: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text, left-aligned, in a colour of its own."""
    content.set_fill(color)
    content.draw_text(font, size, x, y, s)


def text_right(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    right: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text whose right edge sits at ``right``."""
    text(content, font, size, right - font.measure(s, size), y, color, s)


def rule(content: hqf_pdf.Content, y: float, width: float, color: hqf_pdf.Rgb) -> None:
    """A horizontal rule from ``LEFT`` to ``RIGHT`` at height ``y``."""
    content.set_stroke(color)
    content.set_line_width(width)
    content.move_to(LEFT, y)
    content.line_to(RIGHT, y)
    content.stroke()


def invoice_table(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """The invoice's table: a heading row, the billed lines, and the totals."""
    # The description takes whatever the three figure columns leave it.
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(46.0),
            hqf_pdf.ColumnWidth.points(94.0),
            hqf_pdf.ColumnWidth.points(94.0),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, ACCENT))
    table.rule(hqf_pdf.Rule.horizontal_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.78)))
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8, ACCENT))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.8, ACCENT))

    pad = hqf_pdf.Padding.symmetric(6.0, 5.0)
    white = hqf_pdf.Rgb.gray(1.0)

    def heading(label: str, align: hqf_pdf.Align = hqf_pdf.Align.Left) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            padding=pad,
            fill=ACCENT,
            color=white,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
        )

    table.push(
        hqf_pdf.Row(
            [
                heading(words.description),
                heading(words.quantity, hqf_pdf.Align.Right),
                heading(words.unit_price, hqf_pdf.Align.Right),
                heading(words.amount, hqf_pdf.Align.Right),
            ],
            min_height=22.0,
        )
    )

    total = 0.0
    for index, (item, label) in enumerate(zip(ITEMS, words.items)):
        line_total = item.quantity * item.unit_price
        total += line_total

        def figure(value: str) -> hqf_pdf.Cell:
            return hqf_pdf.Cell(
                font,
                9.0,
                value,
                padding=pad,
                align=hqf_pdf.Align.Right,
                valign=hqf_pdf.VAlign.Middle,
            )

        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(font, 9.0, label, padding=pad, valign=hqf_pdf.VAlign.Middle),
                    figure(str(item.quantity)),
                    figure(amount(item.unit_price)),
                    figure(amount(line_total)),
                ],
                min_height=19.0,
                fill=hqf_pdf.Rgb.gray(0.96) if index % 2 else None,
            )
        )

    tax = total * VAT_RATE
    for label, value, size, is_grand_total in (
        (words.subtotal, total, 9.0, False),
        (words.tax, tax, 9.0, False),
        (words.total, total + tax, 10.0, True),
    ):
        # The grand total is boxed off the grid so it reads as a total, not as one more
        # line: the label carries the box's left edge and the figure its right, so the
        # two trace one box between them.
        if is_grand_total:
            stroke = hqf_pdf.Stroke(0.8, ACCENT)
            label_border = hqf_pdf.Border(top=stroke, bottom=stroke, left=stroke)
            value_border = hqf_pdf.Border(top=stroke, bottom=stroke, right=stroke)
            box_margin = hqf_pdf.Margin.symmetric(0.0, 2.0)
        else:
            label_border = value_border = hqf_pdf.Border.none()
            box_margin = hqf_pdf.Margin()

        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(
                        font,
                        size,
                        label,
                        span=3,
                        align=hqf_pdf.Align.Right,
                        padding=pad,
                        margin=box_margin,
                        border=label_border,
                    ),
                    hqf_pdf.Cell(
                        font,
                        size,
                        amount(value),
                        align=hqf_pdf.Align.Right,
                        padding=pad,
                        margin=box_margin,
                        border=value_border,
                    ),
                ],
                min_height=18.0,
            )
        )

    return table


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", f"{words.invoice} {NUMBER}")

    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    logo = document.add_image(hqf_pdf.Image.from_path(LOGO))

    total = sum(item.quantity * item.unit_price for item in ITEMS) * (1.0 + VAT_RATE)

    content = hqf_pdf.Content()

    # The letterhead: the mark, the seller's name and standing, and the word that says
    # what the page is.
    logo_w, logo_h = logo.fit_within(84.0, 84.0)
    content.draw_image(logo, LEFT, 826.5 - logo_h, logo_w, logo_h)

    text(content, font, 8.5, LEFT, 768.0, MUTED, SELLER_ADDRESS)
    text(content, font, 8.5, LEFT, 756.0, MUTED, SELLER_SITE)

    text_right(content, font, 30.0, RIGHT, 796.0, ACCENT, words.heading)
    text_right(content, font, 9.5, RIGHT, 770.0, INK, f"{words.number_label} {NUMBER}")
    text_right(content, font, 9.5, RIGHT, 757.0, MUTED, f"{words.issue_label} {words.issue_date}")
    text_right(content, font, 9.5, RIGHT, 744.0, MUTED, f"{words.due_label} {words.due_date}")

    rule(content, 730.0, 1.2, ACCENT)

    # Who the invoice is to, and — set apart on the right — what it comes to.
    text(content, font, 8.0, LEFT, 712.0, MUTED, words.bill_to)
    text(content, font, 11.0, LEFT, 697.0, INK, BUYER)
    text(content, font, 9.0, LEFT, 683.0, MUTED, BUYER_STREET)
    text(content, font, 9.0, LEFT, 671.0, MUTED, BUYER_CITY)

    text_right(content, font, 8.0, RIGHT, 712.0, MUTED, words.amount_due)
    text_right(content, font, 17.0, RIGHT, 694.0, ACCENT, amount(total))
    text_right(content, font, 9.0, RIGHT, 678.0, MUTED, f"{words.due_short} {words.due_date}")

    # The billed lines, fitted onto this page: the invoice is short enough to sit on
    # one, but the table would continue onto the next were it not.
    table = invoice_table(font, words)
    table_top = 645.0
    placed = table.fit(LEFT, table_top, table_top - 250.0, 0)
    placed.draw(content)
    table_bottom = table_top - placed.height

    # The payment block: how to pay in words, the account in figures, and the same
    # transfer as a code beside it. The due amount is underlined mid-line, which is what
    # rich text is for.
    block_top = table_bottom - 40.0
    text(content, font, 10.0, LEFT, block_top, ACCENT, words.payment)

    body = hqf_pdf.Style(font, 9.5)
    marked = hqf_pdf.Style(font, 9.5, underline=True)
    terms = (
        hqf_pdf.RichText()
        .push(words.terms_before, body)
        .push(amount(total), marked)
        .push(f"{words.terms_around_number}{NUMBER}{words.terms_after}", body)
    )
    terms_top = block_top - 16.0
    lines = terms.break_lines(300.0)
    content.set_fill(INK)
    terms.draw(content, lines, LEFT, terms_top, 300.0)

    iban_y = terms_top - hqf_pdf.RichText.height(lines) - 10.0
    text(content, font, 9.0, LEFT, iban_y, MUTED, words.iban_label)
    text(content, font, 9.5, LEFT + 34.0, iban_y, INK, IBAN_SHOWN)

    # The code sits at the right, drawn as a square from its lower-left corner, level
    # with the payment words and clear of the table above.
    code = hqf_pdf.QrCode(sepa_transfer(words, total))
    side = 104.0
    code_x = RIGHT - side
    code_bottom = block_top + 4.0 - side
    content.set_fill(hqf_pdf.Rgb.gray(0.0))
    content.draw_qr(code, code_x, code_bottom, side)
    text(
        content,
        font,
        8.0,
        code_x + (side - font.measure(words.caption, 8.0)) / 2.0,
        code_bottom - 12.0,
        MUTED,
        words.caption,
    )

    # The foot of the page: what the law asks a French invoice to carry.
    rule(content, 74.0, 0.5, hqf_pdf.Rgb.gray(0.8))
    mentions = (
        f"{SELLER} · {SELLER_ADDRESS} · {SELLER_SIRET} · {SELLER_APE} · "
        f"{words.vat} {SELLER_VAT}"
    )
    text(
        content,
        font,
        7.0,
        LEFT + (TABLE_WIDTH - font.measure(mentions, 7.0)) / 2.0,
        62.0,
        MUTED,
        mentions,
    )

    page = hqf_pdf.Page(PAGE_WIDTH, PAGE_HEIGHT)
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {amount(total)} due")


if __name__ == "__main__":
    main()