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 | //! Lays a whole report out by stacking blocks, without writing a single
//! ordinate by hand.
//!
//! The page holds a title, a rule, two paragraphs, a heading, a table of
//! twenty-six rows and a footnote, and they are pushed onto a stack in the
//! order they are read. The stack breaks them across as many pages as they
//! need: the table is cut row by row, its heading row repeated, and the closing
//! paragraph is kept together so that it is never left with one line on a page
//! of its own.
//!
//! The only ordinate the example writes is the one the page number sits on,
//! which belongs to the sheet rather than to what is said on it. Everything
//! else follows whatever the block above it came to, so a paragraph that grows
//! in translation pushes the rest down instead of being drawn over.
//!
//! Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The hours and the amounts are figures, and stand the
//! same in every language.
//!
//! Usage: `cargo run --example write_stack -- tmp/stack.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_stack -- tmp/pile.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
Align, Block, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stack, StackFrame, Stacked,
Stroke, Table, VAlign,
};
use hqf_pdf::{Document, Font, FontHandle, Page, Rgb, 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 draws with 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")
}
/// The words the report is written in, one set per language.
///
/// What is not language stays out of it: every hour and every amount is a
/// figure, and the row numbers run from one whatever the words say.
#[derive(Debug)]
struct Words {
/// The report's title.
title: &'static str,
/// The paragraph under the title.
intro: &'static str,
/// The heading over the table.
section: &'static str,
/// The three column headings of the table.
headings: [&'static str; 3],
/// What each row of the table is called, before its number.
task: &'static str,
/// The paragraph under the table, kept together.
closing: &'static str,
/// The line at the foot of the report.
footnote: &'static str,
/// The word the page number opens with.
page: &'static str,
/// The word between a page's number and how many pages there are.
of: &'static str,
}
impl Words {
/// The words the report is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
/// What the foot of page `index` of `total` reads.
fn page_label(&self, index: usize, total: usize) -> String {
let number = index + 1;
format!("{} {number} {} {total}", self.page, self.of)
}
/// What row `index` of the table is called.
fn row_label(&self, index: usize) -> String {
let number = index + 1;
format!("{} {number:02}", self.task)
}
}
/// The report in English.
const ENGLISH: Words = Words {
title: "Work carried out this quarter",
intro: "Every block on this page was pushed onto a stack in the order it \
is read, and the stack decided where each of them goes. Nothing here \
was placed against a measured height: a paragraph that grows pushes \
what follows it down the page, and onto the next one when the room \
runs out.",
section: "What was done, task by task",
headings: ["Task", "Hours", "Amount"],
task: "Task",
closing: "The table above was cut wherever the room ran out, and its \
heading row was drawn again at the top of every page it was carried \
onto. This paragraph was kept together, so it is never left with a \
single line at the foot of a page while the rest of it starts the \
next one.",
footnote: "Hours are billed at 85.00 € each, and the amounts are exclusive \
of tax.",
page: "Page",
of: "of",
};
/// The report in French.
const FRENCH: Words = Words {
title: "Les travaux du trimestre",
intro: "Chaque bloc de cette page a été empilé dans l’ordre où on le lit, et c’est la \
pile qui a décidé où chacun se pose. Rien n’a été positionné d’après une \
hauteur mesurée d’avance : un paragraphe qui s’allonge pousse la suite vers le \
bas, et sur la page suivante quand la place vient à manquer.",
section: "Le détail, tâche par tâche",
headings: ["Tâche", "Heures", "Montant"],
task: "Tâche",
closing: "Le tableau ci-dessus a été coupé là où la place manquait, et sa ligne \
d’en-tête répétée en haut de chaque page où il se poursuit. Ce paragraphe, \
lui, reste d’un seul tenant : il ne laisse jamais une ligne seule en bas d’une \
page pendant que le reste ouvre la suivante.",
footnote: "L’heure est facturée 85.00 EUR et les montants s’entendent hors taxes.",
page: "Page",
of: "sur",
};
/// The report in Dutch.
const DUTCH: Words = Words {
title: "Dit kwartaal uitgevoerd werk",
intro: "Elk blok op deze pagina is op een stapel gelegd in de volgorde waarin het gelezen wordt, en de stapel besliste waar elk terechtkomt. Niets hier is tegen een gemeten hoogte geplaatst: een alinea die groeit, duwt wat volgt de pagina af, en naar de volgende als de ruimte op is.",
section: "Wat er gedaan is, taak voor taak",
headings: ["Taak", "Uren", "Bedrag"],
task: "Taak",
closing: "De tabel hierboven is gesneden waar de ruimte op was, en haar koprij is opnieuw getekend bovenaan elke pagina waarnaar ze doorliep. Deze alinea is bij elkaar gehouden, dus blijft ze nooit met één regel onderaan een pagina achter terwijl de rest op de volgende begint.",
footnote: "Uren worden gefactureerd tegen EUR 85,00 per uur, en de bedragen zijn exclusief btw.",
page: "Pagina",
of: "van",
};
/// The report in Portuguese.
const PORTUGUESE: Words = Words {
title: "Trabalho feito este trimestre",
intro: "Cada bloco desta página foi empilhado pela ordem em que se lê, e a pilha decidiu onde vai cada um. Nada aqui foi colocado contra uma altura medida: um parágrafo que cresce empurra o que se segue pela página abaixo, e para a seguinte quando o espaço acaba.",
section: "O que foi feito, tarefa a tarefa",
headings: ["Tarefa", "Horas", "Montante"],
task: "Tarefa",
closing: "A tabela acima foi cortada onde o espaço acabou, e a sua linha de títulos foi redesenhada no topo de cada página para onde passou. Este parágrafo foi mantido junto, por isso nunca fica com uma só linha no fundo de uma página enquanto o resto começa a seguinte.",
footnote: "As horas são faturadas a 85,00 € cada, e os montantes não incluem impostos.",
page: "Página",
of: "de",
};
/// The report in Italian.
const ITALIAN: Words = Words {
title: "Lavoro svolto questo trimestre",
intro: "Ogni blocco di questa pagina è stato impilato nell’ordine in cui si legge, e la pila ha deciso dove va ciascuno. Niente è stato collocato contro un’altezza misurata: un paragrafo che cresce spinge ciò che segue giù per la pagina, e sulla successiva quando lo spazio finisce.",
section: "Cosa si è fatto, attività per attività",
headings: ["Attività", "Ore", "Importo"],
task: "Attività",
closing: "La tabella qui sopra è stata tagliata dove lo spazio finiva, e la sua riga di intestazione è stata ridisegnata in cima a ogni pagina su cui è proseguita. Questo paragrafo è stato tenuto unito, così non resta mai con una sola riga a piè di pagina mentre il resto inizia la successiva.",
footnote: "Le ore sono fatturate a 85,00 € ciascuna, e gli importi si intendono al netto delle imposte.",
page: "Pagina",
of: "di",
};
/// The report in Spanish.
const SPANISH: Words = Words {
title: "Trabajo realizado este trimestre",
intro: "Cada bloque de esta página se apiló en el orden en que se lee, y la pila decidió dónde va cada uno. Nada se colocó contra una altura medida: un párrafo que crece empuja lo que le sigue página abajo, y a la siguiente cuando se acaba el sitio.",
section: "Qué se hizo, tarea a tarea",
headings: ["Tarea", "Horas", "Importe"],
task: "Tarea",
closing: "La tabla de arriba se cortó donde se acabó el sitio, y su fila de títulos se volvió a dibujar arriba de cada página a la que pasó. Este párrafo se mantuvo junto, así que nunca queda con una sola línea al pie de una página mientras el resto empieza la siguiente.",
footnote: "Las horas se facturan a 85,00 € cada una, y los importes no incluyen impuestos.",
page: "Página",
of: "de",
};
/// The report in German.
const GERMAN: Words = Words {
title: "In diesem Quartal ausgeführte Arbeiten",
intro: "Jeder Block auf dieser Seite wurde in der Lesereihenfolge auf einen Stapel gelegt, und der Stapel hat entschieden, wohin jeder kommt. Nichts hier wurde gegen eine gemessene Höhe platziert: Ein wachsender Absatz schiebt das Folgende die Seite hinunter und auf die nächste, wenn der Platz ausgeht.",
section: "Was erledigt wurde, Aufgabe für Aufgabe",
headings: ["Aufgabe", "Stunden", "Betrag"],
task: "Aufgabe",
closing: "Die Tabelle oben wurde dort getrennt, wo der Platz ausging, und ihre Kopfzeile wurde oben auf jeder Seite, auf die sie weiterlief, erneut gezeichnet. Dieser Absatz wurde zusammengehalten, also bleibt nie eine einzelne Zeile unten auf einer Seite zurück, während der Rest die nächste beginnt.",
footnote: "Stunden werden mit je 85,00 € berechnet, und die Beträge verstehen sich ohne Steuer.",
page: "Seite",
of: "von",
};
/// 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),
];
/// How many rows of work the table carries.
const ROWS: usize = 26;
/// The colour of the rule under the title.
const ACCENT: Rgb = Rgb::new(0.12, 0.33, 0.55);
/// The colour the footnote and the page number are set in.
const MUTED: Rgb = Rgb::new(0.45, 0.45, 0.45);
/// How wide the report is, in points: the sheet less a margin either side.
const WIDTH: f64 = 483.0;
/// The left edge of everything the report draws.
const LEFT: f64 = 56.0;
/// The ordinate the page number sits on, which belongs to the sheet rather than
/// to what is said on it.
const FOOT: f64 = 40.0;
/// The box the first page gives the report.
const fn first_box() -> StackFrame {
StackFrame::new(LEFT, 780.0, WIDTH, 700.0)
}
/// The box every page after the first gives it.
const fn next_box() -> StackFrame {
StackFrame::new(LEFT, 780.0, WIDTH, 700.0)
}
/// The hours row `index` took, and what they came to.
fn work(index: usize) -> (u32, u32) {
let hours = 2 + u32::try_from(index % 5).unwrap_or(0);
(hours, hours * 85)
}
/// The table of work, one row per task, its heading row repeated on every page
/// it is carried onto.
#[allow(clippy::expect_used, reason = "three columns fit the report's width")]
fn work_table<'a>(font: &'a FontHandle, words: &'static Words) -> Table<'a> {
let columns = Columns::new(
vec![
ColumnWidth::Fraction(1.0),
ColumnWidth::Points(70.0),
ColumnWidth::Points(90.0),
],
WIDTH,
)
.expect("three columns fit the report's width");
let mut table = Table::new(columns);
table.header(1);
table
.rule(Rule::Frame, Stroke::black(0.8))
.rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.75)))
.rule(Rule::Horizontal(1), Stroke::black(0.8));
let pad = Padding::symmetric(6.0, 5.0);
let heading = |label: &str, align: Align| {
Cell::new(font, 9.0, label)
.align(align)
.padding(pad)
.valign(VAlign::Middle)
.fill(Rgb::gray(0.88))
};
table.push(
Row::new()
.cell(heading(words.headings[0], Align::Left))
.cell(heading(words.headings[1], Align::Right))
.cell(heading(words.headings[2], Align::Right))
.min_height(20.0),
);
for index in 0..ROWS {
let (hours, amount) = work(index);
table.push(
Row::new()
.cell(Cell::new(font, 9.0, words.row_label(index)).padding(pad))
.cell(
Cell::new(font, 9.0, format!("{hours}"))
.align(Align::Right)
.padding(pad),
)
.cell(
Cell::new(font, 9.0, format!("{amount}.00"))
.align(Align::Right)
.padding(pad),
),
);
}
table
}
/// The whole report, block by block, in the order it is read.
fn report<'a>(font: &'a FontHandle, words: &'static Words) -> Stack<'a> {
let mut stack = Stack::new();
stack
.push(Block::text(TextFlow::new(font, 16.0), words.title).keep_together())
.push(Block::space(8.0))
.push(Block::rule(Stroke::new(1.2, ACCENT)))
.push(Block::space(14.0))
.push(Block::text(
TextFlow::new(font, 10.5)
.leading(15.0)
.align(Align::Justify),
words.intro,
))
.push(Block::space(18.0))
.push(Block::text(TextFlow::new(font, 12.0), words.section).keep_together())
.push(Block::space(8.0))
.push(Block::table(work_table(font, words)))
.push(Block::space(18.0))
.push(
Block::text(
TextFlow::new(font, 10.5)
.leading(15.0)
.align(Align::Justify),
words.closing,
)
.keep_together(),
)
.push(Block::space(14.0))
.push(Block::rule(Stroke::new(0.6, MUTED)))
.push(Block::space(8.0))
.push(Block::text(
TextFlow::new(font, 8.0).color(MUTED),
words.footnote,
));
stack
}
/// Draws the page number at the foot of the sheet.
fn page_number(
content: &mut Content,
font: &FontHandle,
words: &Words,
index: usize,
total: usize,
) -> Result<(), hqf_pdf::Error> {
let flow = TextFlow::new(font, 8.0).color(MUTED).align(Align::Center);
let label = words.page_label(index, total);
let lines = flow.break_lines(&label, WIDTH);
content.begin_text();
flow.draw(content, &lines, LEFT, FOOT, WIDTH)?;
content.end_text();
Ok(())
}
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 two languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("stack")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let font = Font::parse(fs::read(&font_path)?)?;
let mut doc = Document::new();
doc.set_license(licence::licensed());
let handle = doc.add_font(font);
let stack = report(&handle, words);
let pages: Vec<Stacked<'_>> = stack.paginate(first_box(), next_box())?;
for (index, placed) in pages.iter().enumerate() {
let mut c = Content::new();
placed.draw(&mut c)?;
page_number(&mut c, &handle, words, index, pages.len())?;
let mut page = Page::a4();
page.content = c.into_bytes();
doc.add_page(page)?;
}
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::layout::StackFrame;
use hqf_pdf::{Document, Font, FontHandle};
use super::{FOOT, ROWS, WIDTH, WORDS, default_font, first_box, language, next_box, report};
/// The lines two languages are allowed to write the same way. "Page" reads
/// the same in both, and the word a reader looks for at the foot of a sheet
/// is not a place to be inventive.
const SPARED: [&str; 5] = [
"page: \"Page\"",
// Written the same way in Portuguese.
r#""Horas""#,
r#"of: "de""#,
r#"page: "Página""#,
// Written the same way in Dutch.
r#"page: "Pagina""#,
];
/// A handle to the committed font, and the document that keeps it alive.
fn font() -> (Document, FontHandle) {
let mut doc = Document::new();
let bytes = std::fs::read(default_font()).expect("the committed font is readable");
let handle = doc.add_font(Font::parse(bytes).expect("the committed font parses"));
(doc, handle)
}
#[test]
fn every_language_draws_the_report_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the report says these in more than one language: {untranslated:?}"
);
}
#[test]
fn every_language_keeps_every_block_inside_the_box_it_was_given() {
let (_doc, handle) = font();
for &(name, words) in &WORDS {
let pages = report(&handle, words)
.paginate(first_box(), next_box())
.expect("the report paginates");
assert!(pages.len() > 1, "{name:?}: the report runs over one page");
for (index, placed) in pages.iter().enumerate() {
let frame: StackFrame = if index == 0 { first_box() } else { next_box() };
let floor = frame.top() - frame.height();
for (block, area) in placed.block_boxes() {
assert!(
area.y() + area.height() <= frame.top() + 1e-9,
"{name:?}: block {block} starts above its box on page {index}"
);
assert!(
area.y() >= floor - 1e-9,
"{name:?}: block {block} reaches below its box on page {index}"
);
assert!(
area.y() > FOOT,
"{name:?}: block {block} lands on the page number"
);
}
}
}
}
#[test]
fn every_line_the_report_writes_on_one_line_fits_the_room_it_has() {
let (_doc, handle) = font();
for &(name, words) in &WORDS {
let single: [(&str, f64, String); 5] = [
("title", 16.0, words.title.to_owned()),
("section", 12.0, words.section.to_owned()),
("page number", 8.0, words.page_label(9, 10)),
("first row", 9.0, words.row_label(0)),
("last row", 9.0, words.row_label(ROWS - 1)),
];
for (what, size, text) in &single {
let width = handle.measure(text, *size);
assert!(
width <= WIDTH,
"{name:?}: the {what} is {width} points wide in {WIDTH}"
);
}
// A heading sits in a column of its own, and the two figure columns
// are the narrowest room on the page.
let headings: [(&str, f64); 3] = [
(words.headings[0], WIDTH - 160.0),
(words.headings[1], 70.0),
(words.headings[2], 90.0),
];
for (heading, room) in &headings {
// The cells are padded six points either side.
let width = handle.measure(heading, 9.0) + 12.0;
assert!(
width <= *room,
"{name:?}: the heading {heading:?} is {width} points wide in {room}"
);
}
}
}
}
|