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 | //! Draws an award certificate on a landscape page: an ornamental double border,
//! a centred title, the recipient's name, the wording of the award, a drawn
//! seal, and two signature lines.
//!
//! Everything ornamental here is a path, not a picture: the border, its corner
//! detail, the ribbon under the seal and the seal itself are built from
//! `move_to` and `line_to`, so the rosette and the star are polygons with
//! enough sides to read as curves. The only image on the page is the mark at
//! the head of it.
//!
//! Every centred line is placed by measuring it with the font and offsetting by
//! half its width, which is what makes the title, the name and the wording sit
//! on one axis.
//!
//! Every word the page draws is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one is drawn. The recipient's name, the
//! signatories' names, the certificate's number and the year on the seal are
//! the same in both.
//!
//! Usage: `cargo run --example write_certificate -- tmp/certificate.pdf
//! [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_certificate --
//! tmp/attestation.pdf`
use std::env;
use std::f64::consts::{FRAC_PI_2, PI};
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{RichText, Style};
use hqf_pdf::{Align, Document, Font, FontHandle, Image, ImageHandle, Page, Rgb};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
use language::Language;
/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The mark at the head of the certificate: the committed fixture, so the
/// example runs on any machine. It stands in for the awarding body's mark.
fn logo_path() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("images")
.join("hqf_development.png")
}
/// A4 turned on its side, in points, and the axis every centred line sits on.
const PAGE_WIDTH: f64 = 841.89;
const PAGE_HEIGHT: f64 = 595.276;
const CENTER: f64 = PAGE_WIDTH / 2.0;
/// How far the two rules of the border stand in from the page edge.
const OUTER_INSET: f64 = 26.0;
const INNER_INSET: f64 = 34.0;
/// The ink the border and the title are drawn in, the black of the name, the
/// grey of the small print, and the two golds of the seal.
const ACCENT: Rgb = Rgb {
r: 0.11,
g: 0.33,
b: 0.55,
};
const INK: Rgb = Rgb {
r: 0.1,
g: 0.1,
b: 0.12,
};
const MUTED: Rgb = Rgb {
r: 0.42,
g: 0.42,
b: 0.45,
};
const GOLD: Rgb = Rgb {
r: 0.66,
g: 0.5,
b: 0.16,
};
const GOLD_PALE: Rgb = Rgb {
r: 0.96,
g: 0.91,
b: 0.78,
};
/// Who is being awarded, and under what number.
const RECIPIENT: &str = "Camille Fontaine";
const NUMBER: &str = "HQF-2026-0731";
/// Who signs the certificate, in the order `Words::roles` gives their roles.
const SIGNATORIES: [&str; 2] = ["Olivier Pons", "Hélène Marchand"];
/// Every word the page draws, in one language.
///
/// What is not language stays out of it: the recipient's name, the signatories'
/// names, the certificate's number and the year on the seal are drawn from
/// constants of their own and read the same in every language.
#[derive(Debug)]
struct Words {
/// The words the document's title is built from, and the words set large
/// across the page.
title: &'static str,
heading: &'static str,
/// The line that stands over the recipient's name.
awarded_to: &'static str,
/// What the programme is called, underlined inside the wording.
programme: &'static str,
/// The wording of the award, cut where the programme's name goes into it.
wording_before: &'static str,
wording_after: &'static str,
/// What each signatory does, in the order `SIGNATORIES` names them.
roles: [&'static str; 2],
/// What stands before the certificate's number, and before the day it was
/// issued, with that day as this language writes it.
number_label: &'static str,
issued_label: &'static str,
issue_date: &'static str,
}
impl Words {
/// The words the certificate is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The certificate in English.
const ENGLISH: Words = Words {
title: "Certificate of Completion",
heading: "CERTIFICATE OF COMPLETION",
awarded_to: "This is to certify that",
programme: "Advanced Document Engineering",
wording_before: "has successfully completed the twelve-week programme in ",
wording_after: ", comprising 96 hours of guided instruction and a supervised \
project, and is commended for the standard of the work presented.",
roles: ["Programme Director", "Head of Certification"],
number_label: "Certificate No.",
issued_label: "Issued",
issue_date: "20 July 2026",
};
/// The certificate in French.
const FRENCH: Words = Words {
title: "Attestation de formation",
heading: "ATTESTATION DE FORMATION",
awarded_to: "Décernée à",
programme: "Ingénierie documentaire avancée",
wording_before: "pour avoir suivi avec succès le programme de douze semaines en ",
wording_after: ", soit 96 heures d'enseignement encadré et un projet \
supervisé, et pour la qualité du travail présenté.",
roles: ["Directeur de programme", "Responsable de la certification"],
number_label: "Attestation n°",
issued_label: "Délivrée le",
issue_date: "20 juillet 2026",
};
/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
[(Language::English, &ENGLISH), (Language::French, &FRENCH)];
/// Where the seal is centred, and how far its scallops reach.
const SEAL_X: f64 = CENTER;
const SEAL_Y: f64 = 186.0;
const SEAL_RADIUS: f64 = 46.0;
/// Draws a line of text, left-aligned, in a colour of its own.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, color: Rgb, s: &str) {
let _ = content.set_fill(color);
content.begin_text();
let _ = content.set_font(font.name(), size);
let _ = content.text_origin(x, y);
content.show_glyphs(&font.glyphs(s));
content.end_text();
}
/// Draws a line of text whose middle sits on `center`.
fn text_center(
content: &mut Content,
font: &FontHandle,
size: f64,
center: f64,
y: f64,
color: Rgb,
s: &str,
) {
text(
content,
font,
size,
center - font.measure(s, size) / 2.0,
y,
color,
s,
);
}
/// The corners of a wheel with `spikes` spikes: `2 * spikes` points around
/// `(cx, cy)`, alternating between the two radii, the first of them straight
/// up.
///
/// Equal radii give a circle drawn as a polygon, and the more spikes it is
/// asked for the rounder it reads; unequal radii give a rosette when they are
/// close and a star when they are far apart.
fn wheel(cx: f64, cy: f64, outer: f64, inner: f64, spikes: u32) -> Vec<(f64, f64)> {
let step = PI / f64::from(spikes);
(0..2 * spikes)
.map(|index| {
let radius = if index % 2 == 0 { outer } else { inner };
let turn = f64::from(index) * step;
let angle = FRAC_PI_2 + turn;
let (dx, dy) = (radius * angle.cos(), radius * angle.sin());
(cx + dx, cy + dy)
})
.collect()
}
/// Adds a closed run of straight segments to the path being built, ready to be
/// filled or stroked. An empty list adds nothing.
fn polygon(content: &mut Content, points: &[(f64, f64)]) -> Result<(), hqf_pdf::Error> {
let Some(&(first_x, first_y)) = points.first() else {
return Ok(());
};
content.move_to(first_x, first_y)?;
for &(x, y) in &points[1..] {
content.line_to(x, y)?;
}
content.line_to(first_x, first_y)?;
Ok(())
}
/// Draws the border: a heavy rule near the page edge, a hairline just inside
/// it, a lozenge on each corner of the hairline and a chamfer cutting across
/// it.
fn border(content: &mut Content) -> Result<(), hqf_pdf::Error> {
let outer_right = PAGE_WIDTH - OUTER_INSET;
let outer_top = PAGE_HEIGHT - OUTER_INSET;
content.set_stroke(ACCENT)?;
content.set_line_width(2.4)?;
content.rect(
OUTER_INSET,
OUTER_INSET,
outer_right - OUTER_INSET,
outer_top - OUTER_INSET,
)?;
content.stroke();
let right = PAGE_WIDTH - INNER_INSET;
let top = PAGE_HEIGHT - INNER_INSET;
content.set_line_width(0.7)?;
content.rect(
INNER_INSET,
INNER_INSET,
right - INNER_INSET,
top - INNER_INSET,
)?;
content.stroke();
// Each corner of the hairline, and the two points 32 into the page along
// its sides that the chamfer runs between.
let near = INNER_INSET + 32.0;
let corners = [
(INNER_INSET, INNER_INSET, near, near),
(right, INNER_INSET, right - 32.0, near),
(INNER_INSET, top, near, top - 32.0),
(right, top, right - 32.0, top - 32.0),
];
for (x, y, chamfer_x, chamfer_y) in corners {
content.move_to(x, chamfer_y)?;
content.line_to(chamfer_x, y)?;
content.stroke();
content.set_fill(ACCENT)?;
polygon(content, &wheel(x, y, 5.5, 5.5, 2))?;
content.fill();
}
Ok(())
}
/// Draws the head of the certificate: the mark, the awarding body's name, and
/// what it is known for.
fn heading(
content: &mut Content,
font: &FontHandle,
logo: &ImageHandle,
) -> Result<(), hqf_pdf::Error> {
let (logo_w, logo_h) = logo.fit_within(96.0, 96.0)?;
content.draw_image(logo, CENTER - logo_w / 2.0, 540.0 - logo_h, logo_w, logo_h)?;
text_center(
content,
font,
8.5,
CENTER,
474.0,
MUTED,
"High Quality Foundations · www.hqf.fr",
);
Ok(())
}
/// Draws what the certificate says: its title over a short rule, the
/// recipient's name over a longer one, and the wording of the award broken to a
/// centred block.
fn award(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), hqf_pdf::Error> {
text_center(content, font, 30.0, CENTER, 424.0, ACCENT, words.heading);
// A rule under the title, parted in the middle by a lozenge.
content.set_stroke(ACCENT)?;
content.set_line_width(1.0)?;
content.move_to(CENTER - 150.0, 410.0)?;
content.line_to(CENTER - 12.0, 410.0)?;
content.stroke();
content.move_to(CENTER + 12.0, 410.0)?;
content.line_to(CENTER + 150.0, 410.0)?;
content.stroke();
content.set_fill(ACCENT)?;
polygon(content, &wheel(CENTER, 410.0, 5.0, 5.0, 2))?;
content.fill();
text_center(content, font, 11.0, CENTER, 383.0, MUTED, words.awarded_to);
text_center(content, font, 34.0, CENTER, 336.0, INK, RECIPIENT);
content.set_stroke(Rgb::gray(0.72))?;
content.set_line_width(0.8)?;
content.move_to(CENTER - 210.0, 321.0)?;
content.line_to(CENTER + 210.0, 321.0)?;
content.stroke();
// The wording, with the programme's name underlined inside the sentence.
let body = Style::new(font, 11.5).color(INK);
let marked = Style::new(font, 11.5).underline().color(INK);
let wording = RichText::new()
.align(Align::Center)
.push(words.wording_before, &body)
.push(words.programme, &marked)
.push(words.wording_after, &body);
let width = 560.0;
let lines = wording.break_lines(width);
wording.draw(content, &lines, CENTER - width / 2.0, 304.0, width)?;
Ok(())
}
/// Draws the seal: two ribbon tails, a scalloped rosette over them, two rings
/// inside it, a star, and the year.
fn seal(content: &mut Content, font: &FontHandle) -> Result<(), hqf_pdf::Error> {
// The two tails, as offsets from the seal's middle: one hanging left, one
// right.
let tails = [
[
(-20.0, -18.0),
(-42.0, -70.0),
(-19.0, -60.0),
(-4.0, -20.0),
],
[(20.0, -18.0), (42.0, -70.0), (19.0, -60.0), (4.0, -20.0)],
];
content.set_fill(GOLD)?;
for tail in tails {
let points: Vec<(f64, f64)> = tail
.iter()
.map(|&(dx, dy): &(f64, f64)| (SEAL_X + dx, SEAL_Y + dy))
.collect();
polygon(content, &points)?;
content.fill();
}
let scallops = wheel(SEAL_X, SEAL_Y, SEAL_RADIUS, SEAL_RADIUS - 6.0, 16);
content.set_fill(GOLD_PALE)?;
polygon(content, &scallops)?;
content.fill();
content.set_stroke(GOLD)?;
content.set_line_width(1.4)?;
polygon(content, &scallops)?;
content.stroke();
content.set_line_width(1.2)?;
polygon(content, &wheel(SEAL_X, SEAL_Y, 33.0, 33.0, 48))?;
content.stroke();
content.set_line_width(0.5)?;
polygon(content, &wheel(SEAL_X, SEAL_Y, 29.0, 29.0, 48))?;
content.stroke();
content.set_fill(GOLD)?;
polygon(content, &wheel(SEAL_X, SEAL_Y + 7.0, 15.0, 6.0, 5))?;
content.fill();
text_center(content, font, 8.0, SEAL_X, SEAL_Y - 23.0, GOLD, "2026");
Ok(())
}
/// Draws the two signature lines, each with a name and a role under it, and the
/// line of small print at the foot of the page.
fn signatures(
content: &mut Content,
font: &FontHandle,
words: &Words,
) -> Result<(), hqf_pdf::Error> {
let centers = [198.0, PAGE_WIDTH - 198.0];
content.set_stroke(Rgb::gray(0.55))?;
content.set_line_width(0.8)?;
for ((center, name), role) in centers.into_iter().zip(SIGNATORIES).zip(words.roles) {
content.move_to(center - 102.0, 128.0)?;
content.line_to(center + 102.0, 128.0)?;
content.stroke();
text_center(content, font, 11.0, center, 112.0, INK, name);
text_center(content, font, 8.5, center, 99.0, MUTED, role);
}
text_center(
content,
font,
7.5,
CENTER,
62.0,
MUTED,
&format!(
"{} {NUMBER} · {} {} · HQF Development, \
42 lot les Genêts, 13480 Calas, France · www.hqf.fr",
words.number_label, words.issued_label, words.issue_date
),
);
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let path = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("certificate")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_info(
Name::new("Title"),
&format!("{} — {RECIPIENT}", words.title),
);
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
let logo = doc.add_image(Image::parse(fs::read(logo_path())?)?);
let mut content = Content::new();
border(&mut content)?;
heading(&mut content, &font, &logo)?;
award(&mut content, &font, words)?;
seal(&mut content, &font)?;
signatures(&mut content, &font, words)?;
let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);
page.content = content.into_bytes();
doc.add_page(page)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &bytes)?;
println!(
"wrote {path}: {} bytes, awarded to {RECIPIENT}",
bytes.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way. There are
/// none: every word is a word of the language it is written in.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_draws_the_certificate_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the certificate says these in more than one language: {untranslated:?}"
);
}
}
|