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
544
545
546
547
548
549
550
551
552
553
554
//! Writes the PDF
//!
//! Every letter is set in a Type0 font with Identity-H. Since glyph IDs can be written as they
//! are, glyphs that no character maps to (such as the brackets in math that stretch) and Japanese
//! text are all handled in the same way.
//! A ToUnicode map is added so that the text can be selected and copied.
//!
//! Content streams are not compressed. This is so that no compression code has to be written, and
//! the file is larger by that amount.
//! A typeface for Japanese text is embedded with only the glyphs in use ([`crate::embed`]).
use crate::draw::{Mark, Page};
use crate::embed;
use crate::font::{self, Face, Library, Outline};
use crate::image::{Color, Picture};
use crate::stream;
use crate::text;
use std::collections::BTreeMap;
/// A destination from a heading
#[derive(Debug, Clone, PartialEq)]
pub struct Destination {
/// The depth. The smaller the value, the larger the heading
pub level: usize,
pub title: String,
/// The page, counted from 0
pub page: usize,
}
/// Collects the contents while giving each one a number
struct Objects {
body: Vec<Vec<u8>>,
}
/// An entry in the nesting of destinations
struct Entry {
level: usize,
title: String,
page: usize,
parent: Option<usize>,
child: Vec<usize>,
number: usize,
}
/// Turns the typeset pages into a PDF
pub fn write(
page: &[Page],
library: &Library,
picture: &[Picture],
title: &str,
destination: &[Destination],
) -> Vec<u8> {
let used = collect(page, library.face.len());
let mut objects = Objects {body: Vec::new()};
let catalog = reserve(&mut objects);
let tree = reserve(&mut objects);
let leaf: Vec<usize> = page.iter().map(|_| reserve(&mut objects)).collect();
let content: Vec<usize> = page.iter().map(|_| reserve(&mut objects)).collect();
let mut font_number: BTreeMap<usize, usize> = BTreeMap::new();
for (index, glyph) in used.iter().enumerate() {
if glyph.is_empty() {
continue;
}
font_number.insert(index, write_font(&mut objects, &library.face[index], glyph));
}
let picture_number: Vec<usize> = picture
.iter()
.map(|one| write_picture(&mut objects, one))
.collect();
let outline = write_outline(&mut objects, destination, &leaf);
let info = reserve(&mut objects);
let resource = describe_resource(&font_number, &picture_number);
for (index, one) in page.iter().enumerate() {
put(
&mut objects,
leaf[index],
format!(
"<< /Type /Page /Parent {tree} 0 R /MediaBox [0 0 {} {}] /Resources {resource} \
/Contents {} 0 R >>",
text::number(one.width),
text::number(one.height),
content[index]
),
);
put_stream(&mut objects, content[index], "", &stream::render(one, library));
}
let kids: Vec<String> = leaf.iter().map(|number| format!("{number} 0 R")).collect();
put(
&mut objects,
tree,
format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",
kids.join(" "),
leaf.len()
),
);
let mut root = format!("<< /Type /Catalog /Pages {tree} 0 R");
if let Some(number) = outline {
root.push_str(&format!(" /Outlines {number} 0 R /PageMode /UseOutlines"));
}
root.push_str(" >>");
put(&mut objects, catalog, root);
put(
&mut objects,
info,
format!(
"<< /Title <{}> /Producer (hongo) /Creator (hongo) /CreationDate ({}) >>",
text::hex_string(title),
text::stamp()
),
);
serialize(&objects, catalog, info)
}
/// Collects the glyphs that are used and their original text, for each typeface
fn collect(page: &[Page], count: usize) -> Vec<BTreeMap<u16, String>> {
let mut found = vec![BTreeMap::new(); count];
for one in page {
for mark in &one.mark {
if let Mark::Text {face, letter, ..} = mark {
if *face >= count {
continue;
}
for letter in letter {
let slot = found[*face].entry(letter.glyph).or_insert_with(String::new);
if slot.is_empty() && !letter.text.is_empty() {
*slot = letter.text.clone();
}
}
}
}
}
found
}
/// Takes one number
fn reserve(objects: &mut Objects) -> usize {
objects.body.push(Vec::new());
objects.body.len()
}
/// Puts the contents in the slot for a number
fn put(objects: &mut Objects, number: usize, body: String) {
objects.body[number - 1] = body.into_bytes();
}
/// Puts a stream in the slot for a number
fn put_stream(objects: &mut Objects, number: usize, head: &str, data: &[u8]) {
let mut body = format!("<< {head} /Length {} >>\nstream\n", data.len()).into_bytes();
body.extend_from_slice(data);
body.extend_from_slice(b"\nendstream");
objects.body[number - 1] = body;
}
/// The typefaces and images that a page refers to
fn describe_resource(
font_number: &BTreeMap<usize, usize>,
picture_number: &[usize],
) -> String {
let mut out = String::from("<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI] /Font <<");
for (face, number) in font_number {
out.push_str(&format!(" /F{face} {number} 0 R"));
}
out.push_str(" >>");
if !picture_number.is_empty() {
out.push_str(" /XObject <<");
for (index, number) in picture_number.iter().enumerate() {
out.push_str(&format!(" /Im{index} {number} 0 R"));
}
out.push_str(" >>");
}
out.push_str(" >>");
out
}
/// Writes the full set of objects for one typeface. Returns the number of the Type0 font
fn write_font(objects: &mut Objects, face: &Face, glyph: &BTreeMap<u16, String>) -> usize {
let type0 = reserve(objects);
let descendant = reserve(objects);
let descriptor = reserve(objects);
let file = reserve(objects);
let to_unicode = reserve(objects);
let program = embed::program(face, &glyph.keys().copied().collect());
let subtype = match face.outline {
Outline::Cff => "CIDFontType0",
Outline::TrueType => "CIDFontType2",
};
let extra = match face.outline {
Outline::Cff => String::new(),
Outline::TrueType => " /CIDToGIDMap /Identity".to_string(),
};
// A subset font gets a tag in its name so that it is not mistaken for the original font
let name = match face.outline {
Outline::Cff => face.name.clone(),
Outline::TrueType => format!("{}+{}", tag(glyph), face.name),
};
put(
objects,
type0,
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{} /Encoding /Identity-H \
/DescendantFonts [{descendant} 0 R] /ToUnicode {to_unicode} 0 R >>",
name
),
);
put(
objects,
descendant,
format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{} \
/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> \
/FontDescriptor {descriptor} 0 R /DW 1000 /W [{}]{extra} >>",
name,
widths(face, glyph)
),
);
put(
objects,
descriptor,
format!(
"<< /Type /FontDescriptor /FontName /{} /Flags {} /FontBBox [{} {} {} {}] \
/ItalicAngle {} /Ascent {} /Descent {} /CapHeight {} /StemV {} /{} {file} 0 R >>",
name,
face.flags,
text::number(face.bbox.0),
text::number(face.bbox.1),
text::number(face.bbox.2),
text::number(face.bbox.3),
text::number(face.italic_angle),
text::number(face.ascent),
text::number(face.descent),
text::number(face.cap_height),
text::number(face.stem),
match face.outline {
Outline::Cff => "FontFile3",
Outline::TrueType => "FontFile2",
}
),
);
let head = match face.outline {
Outline::Cff => "/Subtype /OpenType".to_string(),
Outline::TrueType => format!("/Length1 {}", program.len()),
};
put_stream(objects, file, &head, &program);
put_stream(objects, to_unicode, "", unicode_map(glyph).as_bytes());
type0
}
/// The 6-letter tag for a subset font. It is decided by the glyphs that are used
fn tag(glyph: &BTreeMap<u16, String>) -> String {
let mut value: u32 = 2_166_136_261;
for id in glyph.keys() {
value ^= *id as u32;
value = value.wrapping_mul(16_777_619);
}
let mut out = String::new();
for _ in 0..6 {
out.push((b'A' + (value % 26) as u8) as char);
value /= 26;
}
out
}
/// The advance of each glyph, written in 1/1000 em
fn widths(face: &Face, glyph: &BTreeMap<u16, String>) -> String {
let mut out = String::new();
for id in glyph.keys() {
let width = font::advance(face, *id) * 1000.0;
out.push_str(&format!("{id} [{}] ", text::number(width)));
}
out.trim_end().to_string()
}
/// The map from glyphs to their original text. Used for selecting and copying
fn unicode_map(glyph: &BTreeMap<u16, String>) -> String {
let pair: Vec<(u16, &String)> = glyph
.iter()
.filter(|(_, text)| !text.is_empty())
.map(|(id, text)| (*id, text))
.collect();
let mut out = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n\
/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n\
1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
for block in pair.chunks(100) {
out.push_str(&format!("{} beginbfchar\n", block.len()));
for (id, text) in block {
out.push_str(&format!(
"<{}> <{}>\n",
text::hex_number(*id),
text::hex_string(text).trim_start_matches("FEFF")
));
}
out.push_str("endbfchar\n");
}
out.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
out
}
/// Writes one image
fn write_picture(objects: &mut Objects, picture: &Picture) -> usize {
let number = reserve(objects);
let space = match &picture.color {
Color::Gray => "/DeviceGray".to_string(),
Color::Rgb => "/DeviceRGB".to_string(),
Color::Indexed(table) => {
let mut hex = String::new();
for byte in table {
hex.push_str(&format!("{byte:02X}"));
}
format!("[/Indexed /DeviceRGB {} <{hex}>]", table.len() / 3 - 1)
}
};
let mut head = format!(
"/Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {space} \
/BitsPerComponent {} /Filter /{}",
picture.width, picture.height, picture.bits, picture.filter
);
if !picture.parms.is_empty() {
head.push_str(&format!(" /DecodeParms {}", picture.parms));
}
put_stream(objects, number, &head, &picture.data);
number
}
/// Writes the destinations from the headings. None if there are none
fn write_outline(
objects: &mut Objects,
destination: &[Destination],
leaf: &[usize],
) -> Option<usize> {
if destination.is_empty() || leaf.is_empty() {
return None;
}
let mut entry = nest(destination);
if entry.is_empty() {
return None;
}
let root = reserve(objects);
for one in entry.iter_mut() {
one.number = 0;
}
for index in 0..entry.len() {
entry[index].number = reserve(objects);
}
let top: Vec<usize> = (0..entry.len())
.filter(|index| entry[*index].parent.is_none())
.collect();
put(
objects,
root,
format!(
"<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>",
entry[top[0]].number,
entry[top[top.len() - 1]].number,
entry.len()
),
);
for index in 0..entry.len() {
let body = describe_entry(&entry, index, root, leaf);
put(objects, entry[index].number, body);
}
Some(root)
}
/// Writes one destination
fn describe_entry(entry: &[Entry], index: usize, root: usize, leaf: &[usize]) -> String {
let one = &entry[index];
let parent = match one.parent {
Some(parent) => entry[parent].number,
None => root,
};
let brother: Vec<usize> = match one.parent {
Some(parent) => entry[parent].child.clone(),
None => (0..entry.len())
.filter(|other| entry[*other].parent.is_none())
.collect(),
};
let place = brother.iter().position(|other| *other == index).unwrap_or(0);
let page = leaf[one.page.min(leaf.len() - 1)];
let mut out = format!(
"<< /Title <{}> /Parent {parent} 0 R /Dest [{page} 0 R /XYZ null null null]",
text::hex_string(&one.title)
);
if place > 0 {
out.push_str(&format!(" /Prev {} 0 R", entry[brother[place - 1]].number));
}
if place + 1 < brother.len() {
out.push_str(&format!(" /Next {} 0 R", entry[brother[place + 1]].number));
}
if !one.child.is_empty() {
out.push_str(&format!(
" /First {} 0 R /Last {} 0 R /Count {}",
entry[one.child[0]].number,
entry[one.child[one.child.len() - 1]].number,
count_below(entry, index)
));
}
out.push_str(" >>");
out
}
/// The number of destinations below it
fn count_below(entry: &[Entry], index: usize) -> usize {
let mut total = entry[index].child.len();
for child in &entry[index].child {
total += count_below(entry, *child);
}
total
}
/// Builds the nesting from the sequence of depths
fn nest(destination: &[Destination]) -> Vec<Entry> {
let mut entry: Vec<Entry> = Vec::new();
let mut open: Vec<usize> = Vec::new();
for one in destination {
while let Some(top) = open.last() {
if entry[*top].level >= one.level {
open.pop();
} else {
break;
}
}
let parent = open.last().copied();
let index = entry.len();
entry.push(Entry {
level: one.level,
title: one.title.clone(),
page: one.page,
parent,
child: Vec::new(),
number: 0,
});
if let Some(parent) = parent {
entry[parent].child.push(index);
}
open.push(index);
}
entry
}
/// Puts the collected contents into one file
fn serialize(objects: &Objects, root: usize, info: usize) -> Vec<u8> {
let mut out = b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n".to_vec();
let mut place = Vec::with_capacity(objects.body.len());
for (index, body) in objects.body.iter().enumerate() {
place.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let start = out.len();
out.extend_from_slice(format!("xref\n0 {}\n", objects.body.len() + 1).as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for one in &place {
out.extend_from_slice(format!("{one:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root {root} 0 R /Info {info} 0 R >>\nstartxref\n{start}\n%%EOF\n",
objects.body.len() + 1
)
.as_bytes(),
);
out
}