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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543 | //! Writes a specification sheet whose cells are merged down the rows.
//!
//! Each group of properties names itself once, in a cell covering all the rows
//! of the group, and carries one note beside them in another: the rows beneath
//! hand their cells to the columns those two leave free, and the hairlines
//! between the rows stop at their edges. The last group shows what a merged
//! cell does when it needs more room than its rows give it: every row it covers
//! grows by the same share of what is missing.
//!
//! Usage: `cargo run --example write_merged_cells -- tmp/merged_cells.pdf
//! [font.ttf]`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TableFrame, VAlign,
};
use hqf_pdf::{Align, Document, Font, Page, Rgb};
#[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.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The margin around the table, in points.
const MARGIN: f64 = 56.0;
/// The top of the table on the page.
const TOP: f64 = 760.0;
/// The lowest the table may reach.
const BOTTOM: f64 = 64.0;
/// A4's width, which the table is fitted across.
const PAGE_WIDTH: f64 = 595.276;
/// The width left to the table between the margins.
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;
/// The colour a group's name and its note are painted on.
const GROUP_FILL: Rgb = Rgb::new(0.90, 0.91, 0.94);
/// How many groups the sheet prints, and how many properties in all.
const GROUP_COUNT: usize = 4;
const PROPERTY_COUNT: usize = 11;
/// How many properties each group holds, in the order they are printed.
const GROUP_ROWS: [usize; GROUP_COUNT] = [4, 3, 2, 2];
/// The words the sheet is written in, one set per language.
///
/// What is not language stays out of it: the model's number, the figures and
/// the units they are given in read the same in every language.
#[derive(Debug)]
struct Words {
/// The heading across the four columns.
title: &'static str,
/// What each group is called, written once beside all of its rows.
groups: [&'static str; GROUP_COUNT],
/// What is said about each group as a whole, once beside all of its rows.
/// The last is far longer than the two rows it covers, which is what makes
/// the sheet's last row grow.
notes: [&'static str; GROUP_COUNT],
/// What each property is called, group after group.
properties: [&'static str; PROPERTY_COUNT],
/// What each of them is worth, in the same order.
values: [&'static str; PROPERTY_COUNT],
}
impl Words {
/// The words the sheet is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The sheet in English.
const ENGLISH: Words = Words {
title: "Model HQF-220 — technical data",
groups: ["Body", "Optics", "Mounting", "Power"],
notes: [
"Measured without the mounting plate.",
"Figures hold across the whole of the zoom range.",
"Plate sold with the instrument.",
"Twelve volts, from the adapter supplied or from any regulated bench \
supply. The instrument draws its full current for the first two \
seconds after it is switched on, so a supply rated at the working \
figure alone will trip.",
],
properties: [
"Material",
"Mass",
"Finish",
"Sealing",
"Focal length",
"Widest aperture",
"Coating",
"Thread",
"Plate",
"Supply",
"Draw",
],
values: [
"Anodised aluminium",
"1.84 kg",
"Matt black, bead blasted",
"IP65",
"24 to 70 mm",
"f/2.8",
"Multi-layer, both faces",
"M6, four points",
"Quick release",
"12 V DC",
"9 W at full output",
],
};
/// The sheet in French.
const FRENCH: Words = Words {
title: "Modèle HQF-220 — caractéristiques techniques",
groups: ["Boîtier", "Optique", "Fixation", "Alimentation"],
notes: [
"Mesuré sans la platine de fixation.",
"Valeurs valables sur toute la plage de zoom.",
"Platine livrée avec l’appareil.",
"Douze volts, par l’adaptateur fourni ou par toute alimentation de laboratoire \
régulée. L’appareil appelle son courant maximal pendant les deux premières \
secondes après la mise sous tension : une alimentation calibrée sur la seule \
valeur nominale se mettra en sécurité.",
],
properties: [
"Matériau",
"Masse",
"Finition",
"Étanchéité",
"Focale",
"Ouverture maximale",
"Traitement",
"Filetage",
"Platine",
"Source",
"Consommation",
],
values: [
"Aluminium anodisé",
"1.84 kg",
"Noir mat, microbillé",
"IP65",
"24 à 70 mm",
"f/2.8",
"Multicouche, deux faces",
"M6, quatre points",
"Attache rapide",
"12 V continu",
"9 W à pleine puissance",
],
};
/// The sheet in Dutch.
const DUTCH: Words = Words {
title: "Model HQF-220 — technische gegevens",
groups: ["Behuizing", "Optiek", "Montage", "Voeding"],
notes: [
"Gemeten zonder de montageplaat.",
"De waarden gelden over het hele zoombereik.",
"Plaat meegeleverd met het instrument.",
"Twaalf volt, uit de meegeleverde adapter of uit elke gestabiliseerde labvoeding. Het instrument trekt zijn volle stroom in de eerste twee seconden na het inschakelen, dus een voeding die alleen op de werkwaarde is berekend, schakelt af.",
],
properties: [
"Materiaal",
"Massa",
"Afwerking",
"Afdichting",
"Brandpuntsafstand",
"Grootste diafragma",
"Coating",
"Schroefdraad",
"Plaat",
"Voeding",
"Opgenomen vermogen",
],
values: [
"Geanodiseerd aluminium",
"1,84 kg",
"Matzwart, gestraald",
"IP65",
"24 tot 70 mm",
"f/2,8",
"Meerlaags, beide zijden",
"M6, vier punten",
"Snelkoppeling",
"12 V DC",
"9 W bij vol vermogen",
],
};
/// The sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Modelo HQF-220 — dados técnicos",
groups: ["Corpo", "Ótica", "Montagem", "Alimentação"],
notes: [
"Medido sem a placa de montagem.",
"Os valores mantêm-se em toda a gama do zoom.",
"Placa vendida com o instrumento.",
"Doze volts, do adaptador fornecido ou de qualquer fonte de bancada regulada. O instrumento consome toda a corrente nos dois primeiros segundos após ser ligado, por isso uma fonte dimensionada só para o valor de trabalho vai disparar.",
],
properties: [
"Material",
"Massa",
"Acabamento",
"Estanquidade",
"Distância focal",
"Abertura máxima",
"Tratamento",
"Rosca",
"Placa",
"Alimentação",
"Consumo",
],
values: [
"Alumínio anodizado",
"1,84 kg",
"Preto mate, decapado a esferas",
"IP65",
"24 a 70 mm",
"f/2,8",
"Multicamada, ambas as faces",
"M6, quatro pontos",
"Desengate rápido",
"12 V CC",
"9 W à potência máxima",
],
};
/// The sheet in Italian.
const ITALIAN: Words = Words {
title: "Modello HQF-220 — dati tecnici",
groups: ["Corpo", "Ottica", "Montaggio", "Alimentazione"],
notes: [
"Misurato senza la piastra di montaggio.",
"Le cifre valgono su tutta l’escursione dello zoom.",
"Piastra venduta con lo strumento.",
"Dodici volt, dall’adattatore fornito o da qualsiasi alimentatore da banco stabilizzato. Lo strumento assorbe tutta la corrente nei primi due secondi dopo l’accensione, così un alimentatore dimensionato solo sul valore di lavoro scatterà.",
],
properties: [
"Materiale",
"Massa",
"Finitura",
"Tenuta",
"Lunghezza focale",
"Apertura massima",
"Trattamento",
"Filettatura",
"Piastra",
"Alimentazione",
"Assorbimento",
],
values: [
"Alluminio anodizzato",
"1,84 kg",
"Nero opaco, sabbiato",
"IP65",
"Da 24 a 70 mm",
"f/2,8",
"Multistrato, su entrambe le facce",
"M6, quattro punti",
"Sgancio rapido",
"12 V CC",
"9 W alla massima potenza",
],
};
/// The sheet in Spanish.
const SPANISH: Words = Words {
title: "Modelo HQF-220 — datos técnicos",
groups: ["Cuerpo", "Óptica", "Montaje", "Alimentación"],
notes: [
"Medido sin la placa de montaje.",
"Las cifras valen en todo el rango del zoom.",
"Placa vendida con el instrumento.",
"Doce voltios, del adaptador incluido o de cualquier fuente de banco regulada. El instrumento consume toda su corriente los dos primeros segundos tras encenderse, así que una fuente calculada solo para el valor de trabajo saltará.",
],
properties: [
"Material",
"Masa",
"Acabado",
"Estanqueidad",
"Distancia focal",
"Apertura máxima",
"Tratamiento",
"Rosca",
"Placa",
"Alimentación",
"Consumo",
],
values: [
"Aluminio anodizado",
"1,84 kg",
"Negro mate, microgranallado",
"IP65",
"24 a 70 mm",
"f/2,8",
"Multicapa, ambas caras",
"M6, cuatro puntos",
"Liberación rápida",
"12 V CC",
"9 W a plena potencia",
],
};
/// The sheet in German.
const GERMAN: Words = Words {
title: "Modell HQF-220 — technische Daten",
groups: ["Gehäuse", "Optik", "Befestigung", "Stromversorgung"],
notes: [
"Ohne die Montageplatte gemessen.",
"Die Werte gelten über den ganzen Zoombereich.",
"Die Platte wird mit dem Gerät geliefert.",
"Zwölf Volt, aus dem mitgelieferten Adapter oder einem beliebigen geregelten Labornetzteil. Das Gerät zieht in den ersten zwei Sekunden nach dem Einschalten seinen vollen Strom, also schaltet ein nur für den Betriebswert ausgelegtes Netzteil ab.",
],
properties: [
"Werkstoff",
"Masse",
"Oberfläche",
"Abdichtung",
"Brennweite",
"Größte Blende",
"Vergütung",
"Gewinde",
"Platte",
"Versorgung",
"Aufnahme",
],
values: [
"Eloxiertes Aluminium",
"1.84 kg",
"Mattschwarz, glasperlgestrahlt",
"IP65",
"24 bis 70 mm",
"f/2.8",
"Mehrschichtig, beidseitig",
"M6, vier Punkte",
"Schnellwechsel",
"12 V DC",
"9 W bei voller Leistung",
],
};
/// 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 specification sheet: a heading across the table, then two merged cells
/// per group of properties.
fn sheet<'a>(
text: &'a hqf_pdf::FontHandle,
words: &'static Words,
) -> Result<Table<'a>, hqf_pdf::Error> {
// The property column takes whatever the other three leave it.
let columns = Columns::new(
vec![
ColumnWidth::Points(76.0),
ColumnWidth::Fraction(1.0),
ColumnWidth::Points(120.0),
ColumnWidth::Points(150.0),
],
TABLE_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::VerticalOther, Stroke::new(0.25, Rgb::gray(0.75)))
.rule(Rule::Horizontal(1), Stroke::black(0.8));
let pad = Padding::symmetric(6.0, 5.0);
// The heading covers the four columns, the way a cell covers four rows
// further down: one span across, one down.
table.push(
Row::new()
.cell(
Cell::new(text, 11.0, words.title)
.span(4)
.align(Align::Center)
.valign(VAlign::Middle)
.padding(pad)
.fill(Rgb::gray(0.86)),
)
.min_height(24.0),
);
let mut first = 0;
for (group, &rows) in GROUP_ROWS.iter().enumerate() {
for index in 0..rows {
let property = words.properties[first + index];
let value = words.values[first + index];
let mut row = Row::new();
// The group names itself on its first row only, and so does its
// note. The rows under them hold two cells, not four: the first
// column and the last are taken.
if index == 0 {
row = row.cell(
Cell::new(text, 10.0, words.groups[group])
.span_rows(rows)
.align(Align::Center)
.valign(VAlign::Middle)
.padding(pad)
.fill(GROUP_FILL),
);
}
row = row
.cell(Cell::new(text, 9.0, property).padding(pad))
.cell(Cell::new(text, 9.0, value).padding(pad));
if index == 0 {
row = row.cell(
Cell::new(text, 8.0, words.notes[group])
.span_rows(rows)
.align(Align::Justify)
.padding(pad)
.fill(GROUP_FILL),
);
}
table.push(row.min_height(18.0));
}
first += rows;
}
Ok(table)
}
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("merged_cells")));
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 text = doc.add_font(font);
let table = sheet(&text, words)?;
let placed = table.fit(TableFrame::new(MARGIN, TOP, TOP - BOTTOM), 0)?;
let mut content = Content::new();
placed.draw(&mut content)?;
let mut page = Page::a4();
page.content = content.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, {} rows",
bytes.len(),
table.row_count()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way, each with
/// what makes the two the same word.
const SPARED: [&str; 16] = [
"\"1.84 kg\"",
"\"IP65\"",
"\"f/2.8\"",
// Written the same way in German.
r#""12 V DC""#,
r#""Masse""#,
// Written the same way in Spanish.
r#""Material""#,
// Written the same way in Italian.
r#""1,84 kg""#,
r#""12 V CC""#,
r#""f/2,8""#,
// Written the same way in Portuguese.
r#""24 a 70 mm""#,
r#""Consumo""#,
r#""Corpo""#,
r#""Massa""#,
r#""Placa""#,
r#""Rosca""#,
// Written the same way in Dutch.
r#""Coating""#,
];
#[test]
fn every_language_draws_the_sheet_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the sheet says these in more than one language: {untranslated:?}"
);
}
}
|