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 | """Writes a tender pack: a cover sheet, three files attached to it, and the table a
reading software shows them in.
The Python twin of the `write_portfolio` example in Rust. A document that carries
files is a portfolio when it says how to show them: which columns to lay out, what
each file states for each column, and which way the list is sorted. Without that a
reading software falls back on a list of file names, which tells a buyer nothing
about which lot came in when and for how much.
Each lot is attached as a small XML file, and each states its own lot, the day it was
sent and its total. The columns are declared once on the document, the sort is on the
day, newest first, and the cover sheet lists the files as well, so that a reading
software with no portfolio of its own still shows what is inside.
The dates the columns carry are written the way PDF writes a moment, which is what
`hqf_pdf.pdf_date` turns an ISO 8601 moment into. A file's own `modified` is stated in
ISO 8601 and converted by the library.
Usage: python examples/write_portfolio.py [out.pdf]
HQF_PDF_LANG=fr python examples/write_portfolio.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The margin the page is laid out inside.
MARGIN = 56.0
# How far the page runs across, between the margins.
WIDTH = 483.0
# The name each lot is attached under.
FILES = ("lot-a.xml", "lot-b.xml", "lot-c.xml")
# When each lot was sent, in ISO 8601.
SENT = (
"2026-07-14T09:30:00+02:00",
"2026-08-03T16:05:00+02:00",
"2026-06-28T11:20:00+02:00",
)
# What each lot comes to, in euros.
TOTALS = (18400.0, 9250.0, 31700.0)
# The keys the columns are read under. They are not words anybody is shown: a file
# states its columns under these, and the sort names one of them.
KEYS = ("lot", "sent", "total")
# Where each line of the list sits.
ROWS = (648.0, 626.0, 604.0)
# Where the heading of the list sits.
HEADING = 676.0
# Where each column of the list starts, from the margin.
COLUMNS = (0.0, 96.0, 300.0, 392.0)
@dataclass(frozen=True)
class Words:
"""Every word the page draws, in one language."""
# The line at the head of the page.
title: str
# The paragraph under it.
intro: str
# The heading each column is shown under.
columns: tuple[str, str, str]
# What each lot is called.
lots: tuple[str, str, str]
# What each lot comes to, written the way the language writes money.
totals: tuple[str, str, str]
# The heading over the column of file names.
file_heading: str
# The line under the list.
caption: str
# The page in English.
ENGLISH = Words(
title="Tender pack: three lots",
intro="Every lot of this tender travels in the pack as a file of its own. "
"The document states the columns the files are shown in, what each "
"file holds for each of them, and that the list is sorted on the day "
"it was sent, newest first.",
columns=("Lot", "Sent", "Total"),
lots=(
"Earthworks and site clearance",
"Drainage and services",
"Surfacing and lining",
),
totals=("EUR 18,400.00", "EUR 9,250.00", "EUR 31,700.00"),
file_heading="File",
caption="A reading software that shows a portfolio lays the three files out "
"in these columns. One that does not still opens the pack and "
"lists the files, which is why they are named on this sheet too.",
)
# The page in French.
FRENCH = Words(
title="Dossier d'appel d'offres : trois lots",
intro="Chaque lot de cet appel d'offres voyage dans le dossier comme un "
"fichier à part. Le document dit les colonnes sous lesquelles les "
"fichiers sont présentés, ce que chacun y porte, et que la liste est "
"triée sur le jour de l'envoi, du plus récent au plus ancien.",
columns=("Lot", "Envoyé", "Montant"),
lots=(
"Terrassement et dégagement du terrain",
"Drainage et réseaux",
"Revêtement et marquage",
),
totals=("18 400,00 EUR", "9 250,00 EUR", "31 700,00 EUR"),
file_heading="Fichier",
caption="Un logiciel de lecture qui présente un portefeuille dispose les "
"trois fichiers sous ces colonnes. Celui qui ne le fait pas ouvre "
"tout de même le dossier et liste les fichiers : c'est pourquoi "
"ils sont aussi nommés sur cette feuille.",
)
# 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 day_of(moment: str) -> str:
"""The day of an ISO 8601 moment, which is what the list shows."""
return moment.split("T")[0]
def lot_file(name: str, sent: str, total: float) -> bytes:
"""The file one lot is sent as."""
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
f"<lot>\n <name>{name}</name>\n <sent>{sent}</sent>\n "
f'<total currency="EUR">{total:.2f}</total>\n</lot>\n'
).encode()
def paragraph(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
size: float,
top: float,
color: hqf_pdf.Rgb,
text: str,
) -> None:
"""Writes a paragraph in a column the width of the page."""
flow = hqf_pdf.TextFlow(font, size, leading=size * 1.4, color=color)
lines = flow.break_lines(text, WIDTH)
flow.draw(content, lines, MARGIN, top, WIDTH)
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("portfolio.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
font = document.add_font(hqf_pdf.Font.from_path(_out.DEFAULT_FONT))
for lot in range(len(FILES)):
document.attach(
hqf_pdf.Attachment(
FILES[lot],
words.lots[lot],
"application/xml",
hqf_pdf.Relationship.Source,
SENT[lot],
lot_file(words.lots[lot], SENT[lot], TOTALS[lot]),
)
.stating(KEYS[0], hqf_pdf.CollectionValue.text(words.lots[lot]))
.stating(KEYS[1], hqf_pdf.CollectionValue.date(hqf_pdf.pdf_date(SENT[lot])))
.stating(KEYS[2], hqf_pdf.CollectionValue.number(TOTALS[lot]))
)
document.set_collection(
hqf_pdf.Collection(hqf_pdf.CollectionView.rows())
.with_columns(
[
hqf_pdf.CollectionField(
KEYS[0], words.columns[0], hqf_pdf.CollectionData.text()
),
hqf_pdf.CollectionField(
KEYS[1], words.columns[1], hqf_pdf.CollectionData.date()
),
hqf_pdf.CollectionField(
KEYS[2], words.columns[2], hqf_pdf.CollectionData.number()
),
]
)
.sorted_by(KEYS[1], False)
)
content = hqf_pdf.Content()
content.draw_text(font, 16.0, MARGIN, 780.0, words.title)
paragraph(content, font, 10.0, 750.0, hqf_pdf.Rgb.gray(0.0), words.intro)
headings = (
words.file_heading,
words.columns[0],
words.columns[1],
words.columns[2],
)
for column, heading in zip(COLUMNS, headings):
content.draw_text(font, 9.0, MARGIN + column, HEADING, heading)
content.save_state()
content.set_stroke(hqf_pdf.Rgb.gray(0.75))
content.set_line_width(0.5)
content.move_to(MARGIN, HEADING - 6.0)
content.line_to(MARGIN + WIDTH, HEADING - 6.0)
content.stroke()
content.restore_state()
for lot, at in enumerate(ROWS):
cells = (FILES[lot], words.lots[lot], day_of(SENT[lot]), words.totals[lot])
for column, cell in zip(COLUMNS, cells):
content.draw_text(font, 10.0, MARGIN + column, at, cell)
paragraph(content, font, 8.5, 566.0, hqf_pdf.Rgb.gray(0.35), words.caption)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes, {len(FILES)} files in three columns")
if __name__ == "__main__":
main()
|