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 | //! Writes a one-page price offer whose text cannot be selected, searched,
//! copied or extracted: every letter on the page is a shape traced from the
//! outline of its font, and the file holds no text at all.
//!
//! The page reads as any price offer would. A note at its foot says what was
//! done to it, and what that costs: nothing on the page can be read aloud, the
//! file carries no structure for accessibility, and it is larger.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is written in.
//!
//! Usage: `cargo run --example write_text_as_shapes -- tmp/text_as_shapes.pdf
//! [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_text_as_shapes --
//! tmp/text_as_shapes.fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::Align;
use hqf_pdf::{Document, FontHandle, Page, TextFlow};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
use language::Language;
/// The font the example sets its text in when none is given on the command
/// line: the one committed for the tests, so that the example runs on any
/// machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// How far in from the left and right edges of the sheet the text stands, in
/// points.
const MARGIN: f64 = 56.0;
/// How wide the text runs, in points: the A4 sheet less both margins.
const WIDTH: f64 = 595.0 - 2.0 * MARGIN;
/// How wide the column of amounts is, in points, at the right of the text.
const AMOUNT_WIDTH: f64 = 110.0;
/// How wide the column of what each amount pays for is, in points.
const LABEL_WIDTH: f64 = WIDTH - AMOUNT_WIDTH;
/// Where the top of the first line stands, in points up from the foot of the
/// sheet.
const TOP: f64 = 800.0;
/// How far one row of the price list stands below the one above it, in points.
const ROW: f64 = 20.0;
/// The firm that sends the price offer, written the same way in every language.
const SENDER: &str = "Northfield Acoustics";
/// The amount of each line of the price list, in the order of [`Words::items`].
const AMOUNTS: [&str; 3] = ["1 850.00 EUR", "14 400.00 EUR", "2 200.00 EUR"];
/// The sum of [`AMOUNTS`].
const TOTAL: &str = "18 450.00 EUR";
/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
/// What the document is, set large under the sender.
title: &'static str,
/// The price offer's reference, the day it was issued and how long it
/// holds.
reference: &'static str,
/// Who the price offer is for, and what it is about.
addressee: &'static str,
/// The paragraph saying what the work is.
intro: &'static str,
/// What each amount of the price list pays for, one line each.
items: [&'static str; 3],
/// What the total under the price list is.
total: &'static str,
/// The terms of payment and of the start of the work.
terms: &'static str,
/// The heading of the note at the foot of the page.
note_title: &'static str,
/// The note at the foot of the page, saying that the page holds no text.
note: &'static str,
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Price offer",
reference: "Reference Q-2026-0147 · issued on 2026-10-25 · valid for sixty days",
addressee: "For Harbour Theatre: the acoustics of the main hall",
intro: "Following our visit on 2026-10-12, we propose to measure how the main hall \
answers speech and music, to fit sound-absorbing panels along the side walls and under the \
balcony, and to tune the room once they are up, so that an actor speaking without a \
microphone is heard clearly from the last row.",
items: [
"Survey: acoustic measurements from twelve seats, report",
"Supply and fitting of 48 fabric-covered panels",
"Tuning after fitting, second measurement, final report",
],
total: "Total excluding VAT",
terms: "Prices exclude VAT. Thirty per cent on order, the balance on completion. Work \
can start four weeks after the signed price offer reaches us.",
note_title: "Try to copy a word of this page",
note: "Every letter on this page is a shape traced from the outline of its font: the \
file holds no text at all. A reader sees the price offer exactly as it would otherwise look, \
but can neither select a word, nor search for one, nor copy the prices into another \
document, and a program that extracts text finds nothing. A sender uses this when a \
document must be read but not taken over. What it costs: nothing can be read aloud, there \
is no structure for accessibility, and the file is larger.",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Offre commerciale",
reference: "Référence Q-2026-0147 · date d’émission 2026-10-25 · validité soixante jours",
addressee: "Pour le Harbour Theatre : acoustique de la grande salle",
intro: "À la suite de notre visite du 2026-10-12, nous proposons de mesurer la façon dont la \
grande salle restitue la voix et la musique, de poser des panneaux absorbants le long \
des murs latéraux et sous le balcon, puis de procéder au réglage une fois les panneaux \
posés, afin qu’un comédien parlant sans micro soit entendu distinctement jusqu’au \
dernier rang.",
items: [
"Relevé acoustique depuis 12 fauteuils et rapport",
"Fourniture et pose de 48 panneaux tendus de tissu",
"Réglage après pose, seconde mesure et rapport final",
],
total: "Total hors TVA",
terms: "Prix indiqués hors TVA. Acompte de trente pour cent à la commande, solde à la fin des \
travaux. Les travaux peuvent commencer quatre semaines après réception de l’offre signée.",
note_title: "Essayez de copier un mot de cette page",
note: "Chaque lettre de cette page est une forme tracée d’après le contour de sa police : le \
fichier ne contient aucun texte. Celui qui l’ouvre voit l’offre exactement comme si \
elle était composée normalement, mais il ne peut ni sélectionner ni rechercher un mot, ni \
copier les prix dans un autre document ; un programme d’extraction de texte ne trouve \
rien. On utilise ce procédé quand un document doit être lu sans pouvoir être repris. En \
contrepartie : aucun lecteur d’écran ne peut le lire à voix haute, le document n’a \
aucune structure utile à l’accessibilité, et le fichier est plus lourd.",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Angebot",
reference: "Referenz Q-2026-0147 · ausgestellt am 2026-10-25 · sechzig Tage gültig",
addressee: "Für das Harbour Theatre: Raumakustik des großen Saals",
intro: "Nach unserem Besuch am 2026-10-12 schlagen wir vor, zu messen, wie der große \
Saal auf Sprache und Musik antwortet, entlang der Seitenwände und unter dem Rang \
schallabsorbierende Paneele anzubringen und den Raum danach abzustimmen, damit ein \
Schauspieler ohne Mikrofon bis in die letzte Reihe deutlich zu verstehen ist.",
items: [
"Bestandsaufnahme: Messungen von zwölf Plätzen aus, Bericht",
"Lieferung und Montage von 48 stoffbespannten Paneelen",
"Abstimmung nach der Montage, zweite Messung, Abschlussbericht",
],
total: "Summe ohne MwSt.",
terms: "Preise ohne MwSt. Dreißig Prozent bei Auftragserteilung, der Rest nach \
Abschluss der Arbeiten. Die Arbeiten können vier Wochen nach Eingang des unterschriebenen \
Angebots beginnen.",
note_title: "Versuchen Sie, ein Wort dieser Seite zu kopieren",
note: "Jeder Buchstabe dieser Seite ist eine Form, nachgezeichnet aus dem Umriss seiner \
Schrift: Die Datei enthält überhaupt keinen Text. Der Leser sieht das Angebot genau so, wie \
es sonst aussähe, kann aber weder ein Wort markieren noch danach suchen noch die Preise in \
ein anderes Dokument kopieren, und ein Programm, das Text ausliest, findet nichts. Ein \
Absender nutzt das, wenn ein Dokument gelesen, aber nicht übernommen werden soll. Der Preis \
dafür: Nichts kann vorgelesen werden, es gibt keine Struktur für die Barrierefreiheit, und \
die Datei ist größer.",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Presupuesto",
reference: "Referencia Q-2026-0147 · emitido el 2026-10-25 · válido sesenta días",
addressee: "Para el Harbour Theatre: acústica de la sala principal",
intro: "Tras nuestra visita del 2026-10-12, proponemos medir cómo responde la sala \
principal a la voz y a la música, colocar paneles absorbentes a lo largo de las paredes \
laterales y bajo el anfiteatro, y afinar la sala una vez instalados, para que un actor que \
hable sin micrófono se oiga con claridad desde la última fila.",
items: [
"Estudio: mediciones acústicas desde doce butacas, informe",
"Suministro e instalación de 48 paneles forrados de tela",
"Afinado tras la instalación, segunda medición, informe final",
],
total: "Total sin IVA",
terms: "Precios sin IVA. Un treinta por ciento al hacer el pedido y el resto al \
terminar. Los trabajos pueden empezar cuatro semanas después de recibir el presupuesto \
firmado.",
note_title: "Intente copiar una palabra de esta página",
note: "Cada letra de esta página es una forma trazada a partir del contorno de su \
fuente: el archivo no contiene ningún texto. El lector ve el presupuesto exactamente como se \
vería de otro modo, pero no puede seleccionar una palabra, ni buscarla, ni copiar los \
precios en otro documento, y un programa que extrae texto no encuentra nada. Un remitente lo \
usa cuando un documento debe leerse pero no reutilizarse. Lo que cuesta: nada puede leerse \
en voz alta, no hay estructura para la accesibilidad y el archivo pesa más.",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Preventivo",
reference: "Riferimento Q-2026-0147 · emesso il 2026-10-25 · valido sessanta giorni",
addressee: "Per l’Harbour Theatre: acustica della sala grande",
intro: "Dopo il nostro sopralluogo del 2026-10-12, proponiamo di misurare come la sala \
grande risponde alla voce e alla musica, di montare pannelli fonoassorbenti lungo le pareti \
laterali e sotto la galleria, e di tarare la sala una volta montati, perché un attore che \
parla senza microfono si senta chiaramente fino all’ultima fila.",
items: [
"Rilievo: misure acustiche da dodici poltrone, relazione",
"Fornitura e posa di 48 pannelli rivestiti in tessuto",
"Taratura dopo la posa, seconda misura, relazione finale",
],
total: "Totale IVA esclusa",
terms: "Prezzi IVA esclusa. Il trenta per cento all’ordine, il saldo a fine lavori. I \
lavori possono iniziare quattro settimane dopo il ricevimento del preventivo firmato.",
note_title: "Provate a copiare una parola di questa pagina",
note: "Ogni lettera di questa pagina è una forma tracciata dal contorno del suo \
carattere: il file non contiene alcun testo. Il lettore vede il preventivo esattamente come \
apparirebbe altrimenti, ma non può selezionare una parola, né cercarla, né copiare i prezzi \
in un altro documento, e un programma che estrae il testo non trova nulla. Un mittente lo \
usa quando un documento deve essere letto ma non ripreso. Il costo: nulla può essere letto \
ad alta voce, non c’è struttura per l’accessibilità e il file è più pesante.",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Orçamento",
reference: "Referência Q-2026-0147 · emitido a 2026-10-25 · válido sessenta dias",
addressee: "Para o Harbour Theatre: acústica da sala principal",
intro: "Na sequência da nossa visita de 2026-10-12, propomos medir a forma como a sala \
principal responde à voz e à música, colocar painéis absorventes ao longo das paredes \
laterais e sob o balcão, e afinar a sala depois de colocados, para que um ator que fale sem \
microfone seja ouvido com clareza na última fila.",
items: [
"Levantamento: medições acústicas a partir de doze lugares, relatório",
"Fornecimento e colocação de 48 painéis revestidos a tecido",
"Afinação após a colocação, segunda medição, relatório final",
],
total: "Total sem IVA",
terms: "Preços sem IVA. Trinta por cento com a encomenda, o restante no fim dos \
trabalhos. Os trabalhos podem começar quatro semanas após recebermos o orçamento assinado.",
note_title: "Experimente copiar uma palavra desta página",
note: "Cada letra desta página é uma forma traçada a partir do contorno da sua fonte: o \
ficheiro não contém texto nenhum. O leitor vê o orçamento exatamente como o veria de outra \
forma, mas não consegue selecionar uma palavra, nem procurá-la, nem copiar os preços para \
outro documento, e um programa que extrai texto não encontra nada. Um remetente usa isto \
quando um documento deve ser lido, mas não reaproveitado. O que custa: nada pode ser lido em \
voz alta, não há estrutura para a acessibilidade e o ficheiro fica maior.",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Offerte",
reference: "Referentie Q-2026-0147 · uitgegeven op 2026-10-25 · zestig dagen geldig",
addressee: "Voor het Harbour Theatre: akoestiek van de grote zaal",
intro: "Na ons bezoek op 2026-10-12 stellen we voor te meten hoe de grote zaal op \
spraak en muziek reageert, langs de zijwanden en onder het balkon geluidsabsorberende \
panelen aan te brengen en de zaal daarna af te stemmen, zodat een acteur die zonder \
microfoon spreekt tot op de laatste rij duidelijk te verstaan is.",
items: [
"Opname: akoestische metingen vanaf twaalf stoelen, rapport",
"Levering en montage van 48 met stof beklede panelen",
"Afstemming na montage, tweede meting, eindrapport",
],
total: "Totaal exclusief btw",
terms: "Prijzen exclusief btw. Dertig procent bij bestelling, het saldo na oplevering. \
De werkzaamheden kunnen vier weken na ontvangst van de ondertekende offerte beginnen.",
note_title: "Probeer een woord van deze pagina te kopiëren",
note: "Elke letter op deze pagina is een vorm die is nagetrokken van de omtrek van het \
lettertype: het bestand bevat helemaal geen tekst. De lezer ziet de offerte precies zoals \
die er anders uit zou zien, maar kan geen woord selecteren, er niet naar zoeken en de \
prijzen niet naar een ander document kopiëren, en een programma dat tekst uitleest, vindt \
niets. Een afzender gebruikt dit wanneer een document gelezen maar niet overgenomen mag \
worden. Wat het kost: niets kan worden voorgelezen, er is geen structuur voor \
toegankelijkheid en het bestand is groter.",
};
/// 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); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// The flow one row of the price list sets its label in, and its amount.
fn row_flow(handle: &FontHandle) -> TextFlow<'_> {
TextFlow::new(handle, 10.5).leading(14.0)
}
/// Sets `text` in `flow` across `width` points from `x`, its top at `top`, and
/// returns how tall it stands.
fn set(
content: &mut Content,
flow: &TextFlow<'_>,
text: &str,
x: f64,
top: f64,
width: f64,
) -> hqf_pdf::Result<f64> {
let lines = flow.break_lines(text, width);
content.begin_text();
flow.draw(content, &lines, x, top, width)?;
content.end_text();
Ok(flow.height(&lines))
}
/// A thin grey rule across the text at `y`.
fn rule(content: &mut Content, y: f64) -> hqf_pdf::Result<()> {
content.save_state();
content.set_stroke_rgb(0.6, 0.6, 0.6)?.set_line_width(0.5)?;
content
.move_to(MARGIN, y)?
.line_to(MARGIN + WIDTH, y)?
.stroke();
content.restore_state();
Ok(())
}
/// Sets the whole price offer in `words` onto `content`, from the top of the
/// sheet down, and returns where the last line ends, in points up from the foot
/// of the sheet.
fn compose(content: &mut Content, handle: &FontHandle, words: &Words) -> hqf_pdf::Result<f64> {
let mut top = TOP;
let sender = TextFlow::new(handle, 12.0).leading(15.0);
top -= set(content, &sender, SENDER, MARGIN, top, WIDTH)? + 18.0;
let title = TextFlow::new(handle, 24.0).leading(28.0);
top -= set(content, &title, words.title, MARGIN, top, WIDTH)? + 6.0;
let small = TextFlow::new(handle, 9.5).leading(13.0);
top -= set(content, &small, words.reference, MARGIN, top, WIDTH)? + 4.0;
let addressee = TextFlow::new(handle, 11.0).leading(14.0);
top -= set(content, &addressee, words.addressee, MARGIN, top, WIDTH)? + 18.0;
let body = TextFlow::new(handle, 10.5).leading(15.0);
top -= set(content, &body, words.intro, MARGIN, top, WIDTH)? + 16.0;
let label = row_flow(handle);
let amount = row_flow(handle).align(Align::Right);
for (item, price) in words.items.iter().zip(AMOUNTS) {
set(content, &label, item, MARGIN, top, LABEL_WIDTH)?;
set(
content,
&amount,
price,
MARGIN + LABEL_WIDTH,
top,
AMOUNT_WIDTH,
)?;
top -= ROW;
}
rule(content, top - 2.0)?;
top -= 8.0;
set(content, &label, words.total, MARGIN, top, LABEL_WIDTH)?;
set(
content,
&amount,
TOTAL,
MARGIN + LABEL_WIDTH,
top,
AMOUNT_WIDTH,
)?;
top -= ROW + 12.0;
top -= set(content, &small, words.terms, MARGIN, top, WIDTH)? + 40.0;
rule(content, top)?;
top -= 14.0;
let heading = TextFlow::new(handle, 11.0).leading(14.0);
top -= set(content, &heading, words.note_title, MARGIN, top, WIDTH)? + 4.0;
top -= set(content, &small, words.note, MARGIN, top, WIDTH)?;
Ok(top)
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> 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 languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("text_as_shapes")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(licence::licensed());
let handle = doc.add_font(hqf_pdf::Font::parse(fs::read(&font_path)?)?);
let mut content = Content::new();
compose(&mut content, &handle, words)?;
let mut page = Page::a4();
page.content = content.into_bytes();
doc.add_page(page)?;
// Every letter of the page is written as a shape traced from the font: the
// file holds no text to select, search, copy or extract.
doc.set_text_as_shapes(true);
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&out).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out, &bytes)?;
println!("wrote {out}: {} bytes", bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font};
use super::{LABEL_WIDTH, WORDS, compose, language, row_flow};
/// How low the last line may come, in points up from the foot of the sheet.
const BOTTOM: f64 = 56.0;
/// The lines two languages are allowed to write the same way. There are
/// none: every line is written in the words of its language.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_writes_the_page_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the page says these in more than one language: {untranslated:?}"
);
}
#[test]
fn every_language_holds_each_row_on_one_line_and_the_page_on_the_sheet() {
let font = std::fs::read(super::default_font()).unwrap();
let mut doc = Document::new();
let handle = doc.add_font(Font::parse(font).unwrap());
let label = row_flow(&handle);
for (language, words) in &WORDS {
for row in words.items.iter().chain([&words.total]) {
let lines = label.break_lines(row, LABEL_WIDTH);
assert_eq!(lines.len(), 1, "{}: {row} takes two lines", language.code());
}
let bottom = compose(&mut Content::new(), &handle, words).unwrap();
assert!(
bottom >= BOTTOM,
"{}: the page ends {bottom} pt up from the foot of the sheet, under {BOTTOM}",
language.code()
);
}
}
}
|