Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.2.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
105.5 KB
Downloads
24
Checksum
f438a48f6f2fc61d892f930eb4fb56fb5a8e302e733a8c3a6283d0ff7350cd08
Dependencies
rust/[email protected]
rust/[email protected]

pdf.rs

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
//! PDF を書き出す
//!
//! 字はすべて Type0 の書体を Identity-H で置く。字形の番号をそのまま書けるので、
//! 数式の伸びる括弧のように文字が当たっていない字形も、和文も、同じ道で通る。
//! 選んで写せるように ToUnicode を付ける。
//!
//! 中身の流れは圧縮しない。圧縮を書かずに済ませるためで、そのぶんファイルは大きくなる。
//! 和文の書体は使った字形だけに詰めてから埋める([`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;


/// 見出しからの飛び先
#[derive(Debug, Clone, PartialEq)]
pub struct Destination {
    /// 深さ。小さいほど大きな見出し
    pub level: usize,
    pub title: String,
    /// 0 から数えたページ
    pub page: usize,
}


/// 番号を振りながら中身を集める
struct Objects {
    body: Vec<Vec<u8>>,
}


/// 飛び先の入れ子
struct Entry {
    level: usize,
    title: String,
    page: usize,
    parent: Option<usize>,
    child: Vec<usize>,
    number: usize,
}


/// 組み上がったページを 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)
}


/// 使った字形と、その元の文字を書体ごとに集める
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
}


/// 番号を 1 つ取る
fn reserve(objects: &mut Objects) -> usize {
    objects.body.push(Vec::new());

    objects.body.len()
}


/// 番号のところに中身を入れる
fn put(objects: &mut Objects, number: usize, body: String) {
    objects.body[number - 1] = body.into_bytes();
}


/// 番号のところに流れを入れる
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;
}


/// ページから引く書体と画像
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
}


/// 書体 1 つぶんの一式を書く。返すのは Type0 の番号
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(),
    };
    // 字形を間引いたフォントには、元のものと取り違えないための印を名前に付ける
    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
}


/// 間引いたフォントに付ける 6 文字の印。使った字形から決まる
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
}


/// 字形ごとの送り幅。1000 分の 1 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()
}


/// 字形から元の文字への対応。選んで写すのに使う
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
}


/// 画像 1 つを書く
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
}


/// 見出しからの飛び先を書く。1 つもなければ 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)
}


/// 飛び先 1 つを書く
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
}


/// その下にある飛び先の数
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
}


/// 深さの並びから入れ子を作る
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
}


/// 集めた中身を 1 つのファイルにする
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
}