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 | //! Writes a tagged parts list whose first column is a picture, not a word.
//!
//! A picture says nothing to something that reads a document aloud, so a tagged
//! file has to say it instead: each picture is marked as a figure of its own
//! and carries the words a reader hears in its place. That is what `Cell::alt`
//! is for, and this is what it comes to — a table whose every row is a row of
//! the structure tree, whose text cells are read as text, and whose picture
//! cells are read as the sentence the catalogue gave them.
//!
//! The tree is not built by hand here: the table hands back the branch
//! describing itself, figures and all, from the same counter the page numbers
//! its marks from. That is what keeps a number in the stream and a number in
//! the tree from drifting apart.
//!
//! Where [`write_tagged`](write_tagged) shows prose, headings and a table of
//! figures, this shows the one thing prose cannot: a picture inside a cell,
//! standing for something a reader must be told about.
//!
//! The list is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is written. The language a document is in is part of what makes it
//! readable aloud: the structure tree carries the tag of the language its words
//! are in, and it comes from the same set of words as the words themselves.
//!
//! Usage: `cargo run --example write_tagged_pictures -- tmp/tagged_pictures.pdf
//! [font.ttf]`
//! `cargo run --example write_tagged_pictures -- tmp/out.pdf --archival`
//! `cargo run --example write_tagged_pictures -- tmp/out.pdf --ua`
//! `HQF_PDF_LANG=fr cargo run --example write_tagged_pictures --
//! tmp/pieces.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{
Align, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TextFlow, VAlign,
};
use hqf_pdf::metadata::xmp::{Metadata, PdfA, PdfUa};
use hqf_pdf::{
Artifact, Document, Font, FontHandle, Image, ImageHandle, License, Marks, Page, Rgb,
StructElement, StructureTree,
};
#[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 pictures the list shows, committed with the tests.
fn pictures() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("images")
}
/// The left edge everything is set from, and the room it all has.
const MARGIN: f64 = 64.0;
/// The room the table has across an A4 page between the margins.
const WIDTH: f64 = 595.276 - 2.0 * MARGIN;
/// The colour the heading row is painted on.
const HEAD_FILL: Rgb = Rgb::gray(0.88);
/// How many parts the list holds.
const PARTS: usize = 3;
/// The picture each part is shown by, under the committed images. A picture is
/// the same picture in every language.
const PICTURES: [&str; PARTS] = ["logo.png", "hqf_development.png", "indexed_16colours.png"];
/// The words the list is written in, one set per language.
///
/// The tag of the language is here too: a document that says nothing about the
/// language its words are in cannot be read aloud properly, and it is one more
/// thing a set of words has to get right.
#[derive(Debug)]
struct Words {
/// The tag the structure tree carries, saying what the words below are in.
lang: &'static str,
/// The title the document is filed under, in its information dictionary and
/// in its metadata both.
title: &'static str,
/// The line at the head of the page.
heading: &'static str,
/// The heading of each column, in the order the columns are set.
columns: [&'static str; 3],
/// What each part is called, in the order the rows are written.
names: [&'static str; PARTS],
/// What each part is for.
purposes: [&'static str; PARTS],
/// What each picture is, said in words. A figure with nothing here is a
/// figure nothing can read out, and a validator says so.
alts: [&'static str; PARTS],
/// The paragraph under the list.
closing: &'static str,
/// The page number at the foot, which is furniture rather than what the
/// document says.
footer: &'static str,
}
impl Words {
/// The words the list is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The list in English.
const ENGLISH: Words = Words {
lang: "en-GB",
title: "A tagged parts list",
heading: "Parts of the housing",
columns: ["Picture", "Part", "What it is for"],
names: ["Cover plate", "Rating label", "Heat scale"],
purposes: [
"Closes the housing once the board is seated.",
"Carries the serial number and the supply it is rated for.",
"Read against the winding to say how hot it is running.",
],
alts: [
"The house mark: a ring, one half blue and the other yellow.",
"The maker's name, printed across the label in full.",
"A band running from red at the top down to blue at the bottom.",
],
closing: "Every picture above is marked as a figure and carries the words a \
reader hears in its place, so nothing in this list is lost on somebody \
who cannot see it. The table itself is a branch of the structure tree: \
each row is a row there too, and each cell says which column it sits \
in.",
footer: "Page 1 of 1",
};
/// The list in French.
const FRENCH: Words = Words {
lang: "fr-FR",
title: "Une liste de pièces balisée",
heading: "Les pièces du boîtier",
columns: ["Image", "Pièce", "À quoi elle sert"],
names: ["Couvercle", "Plaque signalétique", "Échelle de chaleur"],
purposes: [
"Ferme le boîtier une fois la carte en place.",
"Porte le numéro de série et la tension prévue.",
"Se lit contre le bobinage pour dire à quelle chaleur il tourne.",
],
alts: [
"La marque de la maison : un anneau, moitié bleu, moitié jaune.",
"Le nom du fabricant, imprimé en entier sur l'étiquette.",
"Une bande qui va du rouge en haut au bleu en bas.",
],
closing: "Chaque image ci-dessus est marquée comme figure et porte les mots \
qu'un lecteur entend à sa place : rien de cette liste n'échappe à qui \
ne la voit pas. Le tableau lui-même est une branche de l'arbre de \
structure : chaque rangée y est une rangée aussi, et chaque cellule dit \
dans quelle colonne elle se trouve.",
footer: "Page 1 sur 1",
};
/// 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)];
/// Draws one line of text with its baseline at `(x, y)`, at `size` points.
fn text(
content: &mut Content,
font: &FontHandle,
size: f64,
x: f64,
y: f64,
line: &str,
) -> Result<(), hqf_pdf::Error> {
content.begin_text();
content.set_font(font.name(), size)?;
content.text_origin(x, y)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
Ok(())
}
/// The heading, marked and numbered so that the tree can point at it.
fn heading(
content: &mut Content,
font: &FontHandle,
marks: &mut Marks,
page: usize,
words: &'static Words,
) -> Result<StructElement, hqf_pdf::Error> {
let id = marks.next_id();
content.begin_tagged(&Name::new("H1"), id);
text(content, font, 18.0, MARGIN, 762.0, words.heading)?;
content.end_marked();
Ok(StructElement::new("H1").content(page, id))
}
/// The closing paragraph, broken into lines and marked as one run.
fn closing(
content: &mut Content,
font: &FontHandle,
marks: &mut Marks,
page: usize,
top: f64,
words: &'static Words,
) -> Result<StructElement, hqf_pdf::Error> {
let flow = TextFlow::new(font, 10.0)
.leading(15.0)
.align(Align::Justify);
let lines = flow.break_lines(words.closing, WIDTH);
// The flow writes the text operators and nothing around them, so the caller
// opens and closes the text object itself.
content.begin_text();
let numbers = flow.draw_tagged(content, &lines, MARGIN, top, WIDTH, &Name::new("P"), marks)?;
content.end_text();
let number = numbers
.first()
.copied()
.expect("the paragraph is one marked run");
Ok(StructElement::new("P").content(page, number))
}
/// The parts list, and the branch of the tree describing it.
///
/// The pictures are drawn by the table, each into whatever rectangle its cell
/// came to, and each marked as a figure carrying its own words.
fn list(
content: &mut Content,
font: &FontHandle,
handles: &[ImageHandle],
marks: &mut Marks,
page: usize,
words: &'static Words,
) -> Result<(StructElement, f64), hqf_pdf::Error> {
let mut table = Table::new(Columns::new(
vec![
ColumnWidth::Points(96.0),
ColumnWidth::Points(120.0),
ColumnWidth::Points(WIDTH - 216.0),
],
WIDTH,
)?);
table.header(1);
table.rule(Rule::Frame, Stroke::black(0.8));
table.rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.7)));
let mut head = Row::new().fill(HEAD_FILL);
for label in words.columns {
head = head.cell(
Cell::new(font, 10.0, label)
.align(Align::Left)
.padding(Padding::symmetric(6.0, 5.0)),
);
}
table.push(head);
for ((handle, name), (purpose, alt)) in handles
.iter()
.zip(words.names)
.zip(words.purposes.into_iter().zip(words.alts))
{
table.push(
Row::new()
.min_height(54.0)
.cell(
Cell::image(handle)
.alt(alt)
.align(Align::Center)
.valign(VAlign::Middle)
.padding(Padding::uniform(5.0)),
)
.cell(
Cell::new(font, 10.0, name)
.valign(VAlign::Middle)
.padding(Padding::symmetric(6.0, 5.0)),
)
.cell(
Cell::new(font, 10.0, purpose)
.valign(VAlign::Middle)
.padding(Padding::symmetric(6.0, 5.0)),
),
);
}
let placement = table.fit(MARGIN, 736.0, 620.0, 0)?;
let bottom = placement.bottom();
Ok((placement.draw_tagged(content, page, marks)?, bottom))
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args: Vec<String> = env::args().skip(1).collect();
let evaluation = args.iter().any(|arg| arg == "--evaluation");
// Level A is the level that demands the structure tree, which is the whole
// subject here.
let archival = args.iter().any(|arg| arg == "--archival");
let ua = args.iter().any(|arg| arg == "--ua");
args.retain(|arg| !arg.starts_with("--"));
let mut args = args.into_iter();
// 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("tagged_pictures")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(if evaluation {
License::evaluation()
} else {
licence::licensed()
});
if archival {
doc.set_conformance(PdfA::A3A);
}
if ua {
doc.set_ua_conformance(PdfUa::One);
}
if archival || ua {
doc.set_metadata(Metadata {
title: Some(words.title.to_owned()),
producer: Some("hqf-pdf".to_owned()),
created: Some("2026-07-26T09:30:00+02:00".to_owned()),
..Metadata::default()
});
}
doc.set_info(Name::new("Title"), words.title);
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
let mut handles = Vec::with_capacity(PARTS);
for picture in PICTURES {
handles.push(doc.add_image(Image::parse(fs::read(pictures().join(picture))?)?));
}
let mut content = Content::new();
let mut marks = Marks::new();
let mut section = StructElement::new("Sect");
section = section.child(heading(&mut content, &font, &mut marks, 0, words)?);
let (table, bottom) = list(&mut content, &font, &handles, &mut marks, 0, words)?;
section = section.child(table);
section = section.child(closing(
&mut content,
&font,
&mut marks,
0,
bottom - 24.0,
words,
)?);
// The page number is furniture, not what the document says, so it carries
// no number and the tree never points at it.
content.begin_artifact(Artifact::Footer);
text(&mut content, &font, 9.0, MARGIN, 48.0, words.footer)?;
content.end_marked();
let mut page = Page::a4();
page.content = content.into_bytes();
doc.add_page(page)?;
doc.set_structure(
StructureTree::new()
.lang(words.lang)
.child(StructElement::new("Document").child(section)),
);
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &bytes)?;
println!("wrote {} ({} bytes)", path, bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use super::{PARTS, WORDS, language};
/// The lines two languages are allowed to write the same way. Every line
/// here is a sentence, a name or a language tag, and no two languages write
/// one alike.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_writes_the_list_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the list says these in more than one language: {untranslated:?}"
);
}
/// The words a reader hears in place of a picture say what the picture is.
/// A language that repeats the name of the part there leaves that reader
/// with the row's own text twice over and nothing about the picture.
#[test]
fn every_language_says_what_each_picture_is_rather_than_naming_the_part() {
for (language, words) in WORDS {
for index in 0..PARTS {
let alt = words.alts[index];
assert!(
!alt.is_empty(),
"{} leaves picture {index} without words",
language.code()
);
assert_ne!(
alt,
words.names[index],
"{} hears the name of picture {index} rather than the picture",
language.code()
);
}
}
}
}
|