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 | //! Sets paragraphs whose style changes inside them: sizes that shift mid-line,
//! a total that is underlined, and a word that turns underlined halfway
//! through.
//!
//! Each block is laid out in the same box, so a line is as tall as the tallest
//! style standing on it, and an underline is drawn where each font says one
//! goes.
//!
//! The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG`
//! picks which set is set. Each is cut around the run whose style changes, so
//! that a language says what it has to say around the same three pieces.
//!
//! Usage: `cargo run --example write_rich_text -- tmp/rich.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_rich_text -- tmp/riche.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{RichText, Style};
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;
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 left edge of every box, in points.
const LEFT: f64 = 56.0;
/// The width every paragraph is broken to.
const WIDTH: f64 = 420.0;
/// The top of the first box.
const TOP: f64 = 760.0;
/// The gap between one block and the next.
const GAP: f64 = 26.0;
/// The sum the first paragraph is about. A total is not language.
const AMOUNT: &str = "1 240.00 EUR";
/// The words the page is set in, one set per language.
///
/// Every paragraph is cut around the run that carries the style being shown, so
/// the piece that is underlined, enlarged or coloured is a piece of the
/// sentence rather than a sentence of its own.
#[derive(Debug)]
struct Words {
/// The line at the head of the page.
title: &'static str,
/// The first paragraph, cut around the amount it names.
due: [&'static str; 2],
/// The second, cut around the run set in the largest type.
tallest: [&'static str; 3],
/// The third, cut around the run that carries its own colour.
coloured: [&'static str; 3],
/// The fourth, cut in the middle of a word: the second piece turns
/// underlined without the word being broken at the join.
joined: [&'static str; 3],
/// The fifth, cut around the run named by the alignment it is set to.
small: [&'static str; 3],
}
impl Words {
/// The words the page is set in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Rich text: styles, sizes, underlining, colour",
due: [
"The amount due is ",
", payable within thirty days. The balance carries interest at the \
statutory rate from the day it falls due, and no reminder has to be \
sent for it to do so.",
],
tallest: [
"A line is as tall as ",
"the largest",
" of the styles standing on it, and no taller.",
],
coloured: [
"A run can carry its own ",
"colour",
", set apart from the black around it.",
],
joined: [
"A word may change style in the middle: under",
"lined",
" is still one word, and is never broken at the join.",
],
small: [
"The small print sits in small type, ",
"flush right",
", below the body of the text.",
],
};
/// The page in French.
const FRENCH: Words = Words {
title: "Texte enrichi : styles, tailles, soulignement, couleur",
due: [
"Le montant dû est de ",
", payable sous trente jours. Le solde porte intérêt au taux légal à \
compter du jour de son échéance, sans qu'aucun rappel n'ait à être \
envoyé.",
],
tallest: [
"Une ligne est aussi haute que ",
"le plus grand",
" des styles qui s'y tiennent, et pas davantage.",
],
coloured: [
"Un passage peut porter sa propre ",
"couleur",
", distincte du noir qui l'entoure.",
],
joined: [
"Un mot peut changer de style en son milieu : souli",
"gné",
" reste un seul mot, et n'est jamais coupé à la jointure.",
],
small: [
"Les mentions légales sont en petits caractères, ",
"alignées à droite",
", sous le corps du texte.",
],
};
/// 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)];
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 out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("rich")));
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 regular = Style::new(&text, 11.0);
let small = Style::new(&text, 8.0);
let large = Style::new(&text, 17.0);
let marked = Style::new(&text, 11.0).underline();
let accent = Style::new(&text, 11.0).color(Rgb::new(0.0, 0.35, 0.7));
let blocks = vec![
RichText::new()
.align(Align::Justify)
.push(words.due[0], ®ular)
.push(AMOUNT, &marked)
.push(words.due[1], ®ular),
RichText::new()
.push(words.tallest[0], ®ular)
.push(words.tallest[1], &large)
.push(words.tallest[2], ®ular),
RichText::new()
.push(words.coloured[0], ®ular)
.push(words.coloured[1], &accent)
.push(words.coloured[2], ®ular),
RichText::new()
.push(words.joined[0], ®ular)
.push(words.joined[1], &marked)
.push(words.joined[2], ®ular),
RichText::new()
.align(Align::Right)
.push(words.small[0], &small)
.push(words.small[1], &small)
.push(words.small[2], &small),
];
let mut content = Content::new();
content.begin_text();
content.set_font(text.name(), 14.0)?;
content.text_origin(LEFT, TOP + 24.0)?;
content.show_glyphs(&text.glyphs(words.title));
content.end_text();
let mut top = TOP;
for block in &blocks {
let lines = block.break_lines(WIDTH);
block.draw(&mut content, &lines, LEFT, top, WIDTH)?;
top -= RichText::height(&lines) + GAP;
}
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, {} blocks",
bytes.len(),
blocks.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way. Every
/// paragraph here is a sentence, and no two languages write one alike.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_sets_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:?}"
);
}
/// The fourth paragraph exists to show that a word whose halves are set in
/// two styles is still one word. A language that gives the underlined run a
/// word of its own shows nothing, and the page reads as if the run had been
/// emphasised in the ordinary way.
#[test]
fn every_language_turns_a_word_underlined_halfway_through() {
for (language, words) in WORDS {
let [before, run, after] = words.joined;
let code = language.code();
assert!(
!before.ends_with(' '),
"{code} starts the underlined run on a word of its own"
);
assert!(
!run.starts_with(' ') && !run.ends_with(' '),
"{code} pads the underlined run with spaces"
);
assert!(
after.starts_with(' '),
"{code} carries the word on past the underlining"
);
}
}
}
|