docxide-pdf 0.16.3

Library and CLI for converting DOCX files to PDF, matching Microsoft Word's output as closely as possible
Documentation
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
use std::collections::{HashMap, HashSet};

use pdf_writer::{Pdf, Ref};

use crate::fonts::{FontEntry, font_key_buf, register_font};
use crate::model::{
    Block, Document, FieldCode, Paragraph, Run,
};

use super::header_footer::hf_paragraphs;
use super::{collect_paras, label_font_key, para_runs_with_textboxes};

pub(super) fn collect_all_runs(doc: &Document) -> Vec<&Run> {
    let hf_runs = doc.sections.iter().flat_map(|s| {
        [
            &s.properties.header_default,
            &s.properties.header_first,
            &s.properties.header_even,
            &s.properties.footer_default,
            &s.properties.footer_first,
            &s.properties.footer_even,
        ]
        .into_iter()
        .filter_map(|hf| hf.as_ref())
        .flat_map(|hf| hf_paragraphs(hf))
        .flat_map(|p| para_runs_with_textboxes(p))
    });

    let footnote_runs = doc
        .footnotes
        .values()
        .flat_map(|fn_| fn_.paragraphs.iter())
        .flat_map(|p| para_runs_with_textboxes(p));

    let endnote_runs = doc
        .endnotes
        .values()
        .flat_map(|en| en.paragraphs.iter())
        .flat_map(|p| para_runs_with_textboxes(p));

    doc.sections
        .iter()
        .flat_map(|s| s.blocks.iter())
        .flat_map(|block| -> Vec<&Run> {
            match block {
                Block::Paragraph(para) => para_runs_with_textboxes(para),
                Block::Table(table) => table
                    .rows
                    .iter()
                    .flat_map(|row| row.cells.iter())
                    .flat_map(|cell| cell.all_paragraphs())
                    .flat_map(|para| para_runs_with_textboxes(para))
                    .collect(),
            }
        })
        .chain(hf_runs)
        .chain(footnote_runs)
        .chain(endnote_runs)
        .collect()
}

fn collect_used_chars(doc: &Document, all_runs: &[&Run]) -> HashMap<String, HashSet<char>> {
    let mut used: HashMap<String, HashSet<char>> = HashMap::new();
    let mut key_buf = String::new();

    // §17.11.18/.17 mark numbering formats — must mirror the render pre-pass
    // (src/pdf/mod.rs) so the subset embeds the glyphs the marks actually use.
    // Without this, a non-decimal format (e.g. upperRoman "I"/"II", lowerLetter
    // "b") whose letters never appear in body text gets dropped from the subset
    // and renders as a missing glyph.
    let fn_mark_fmt = doc
        .sections
        .iter()
        .find_map(|s| s.properties.footnote_num_fmt.as_deref())
        .unwrap_or("decimal");
    let en_mark_fmt = doc
        .sections
        .iter()
        .find_map(|s| s.properties.endnote_num_fmt.as_deref())
        .unwrap_or("lowerRoman");

    for run in all_runs {
        let key = font_key_buf(run, &mut key_buf);
        let chars = used.entry(key.to_string()).or_default();
        if run.caps || run.small_caps {
            chars.extend(run.text.to_uppercase().chars());
        } else {
            chars.extend(run.text.chars());
        }
        if let Some(ref fc) = run.field_code {
            match fc {
                FieldCode::Page | FieldCode::NumPages | FieldCode::PageRef(_) => {
                    chars.extend('0'..='9');
                }
                FieldCode::StyleRef(_) => {}
            }
        }
        if run.footnote_id.is_some() || run.is_footnote_ref_mark {
            chars.extend('0'..='9');
            extend_chars_for_num_format(chars, fn_mark_fmt);
        }
        if run.endnote_id.is_some() || run.is_endnote_ref_mark {
            chars.extend('0'..='9');
            extend_chars_for_num_format(chars, en_mark_fmt);
        }
    }

    let mut all_paras: Vec<&Paragraph> = doc
        .sections
        .iter()
        .flat_map(|s| s.blocks.iter())
        .flat_map(|block| -> Vec<&Paragraph> {
            match block {
                Block::Paragraph(p) => collect_paras(p),
                Block::Table(t) => t
                    .rows
                    .iter()
                    .flat_map(|row| row.cells.iter())
                    .flat_map(|cell| cell.all_paragraphs())
                    .flat_map(|p| collect_paras(p))
                    .collect(),
            }
        })
        .collect();
    for note in doc.footnotes.values().chain(doc.endnotes.values()) {
        for p in &note.paragraphs {
            all_paras.extend(collect_paras(p));
        }
    }

    for para in &all_paras {
        if !para.list_label.is_empty() {
            if let Some(key) = label_font_key(para) {
                used.entry(key)
                    .or_default()
                    .extend(para.list_label.chars());
            }
            // The label may fall back to the surrounding body font when the
            // labeled font (e.g. Symbol) can't render a PUA bullet char. Make
            // sure the body font's subset includes the Unicode substitute.
            if let Some(run) = para.runs.first() {
                let body_key = font_key_buf(run, &mut key_buf).to_string();
                let entry = used.entry(body_key).or_default();
                for c in para.list_label.chars() {
                    if let Some(sub) = super::list_label::symbol_pua_to_unicode(c) {
                        entry.insert(sub);
                    }
                }
            }
        }
        for stop in &para.tab_stops {
            if let Some(leader_char) = stop.leader
                && let Some(run) = para.runs.first()
            {
                let key = font_key_buf(run, &mut key_buf).to_string();
                used.entry(key).or_default().insert(leader_char);
            }
        }
    }

    // Collect SmartArt text chars into the default document font (for shapes
    // without per-run font names, which fall back to the global SmartArt font)
    if let Some(first_run) = all_runs.first() {
        let sa_key = font_key_buf(first_run, &mut key_buf).to_string();
        let chars = used.entry(sa_key).or_default();
        for para in &all_paras {
            for diagram in &para.smartart {
                for shape in &diagram.shapes {
                    for sa_para in &shape.paragraphs {
                        for run in &sa_para.runs {
                            if run.font_name.is_none() {
                                chars.extend(run.text.chars());
                            }
                        }
                        if let Some(ref b) = sa_para.bullet {
                            chars.extend(b.chars());
                        }
                    }
                }
            }
        }
    }

    // Comments rendered in the right-side pane use the body font for the
    // comment text and the body font's bold variant for the "Commented [Rn]:"
    // label. Pick the body font from the first NON-bold, NON-italic run we can
    // find (headings are typically bold and would otherwise point us at the
    // wrong face); fall back to the first run if nothing else matches.
    if !doc.comments.is_empty() {
        let body_run = all_runs
            .iter()
            .find(|r| !r.bold && !r.italic)
            .or_else(|| all_runs.first())
            .copied();
        if let Some(body_run) = body_run {
            let mut reg = (*body_run).clone();
            reg.bold = false;
            reg.italic = false;
            let reg_key = font_key_buf(&reg, &mut key_buf).to_string();
            let mut bold = (*body_run).clone();
            bold.bold = true;
            bold.italic = false;
            let bold_key = font_key_buf(&bold, &mut key_buf).to_string();

            let regular = used.entry(reg_key).or_default();
            for comment in doc.comments.values() {
                regular.extend(comment.text.chars());
            }

            let bold = used.entry(bold_key).or_default();
            for comment in doc.comments.values() {
                bold.extend("Commented []: ".chars());
                bold.extend(comment.initials.chars());
                bold.extend(comment.display_index.to_string().chars());
            }
        }
    }

    // Collect characters that may appear in STYLEREF values by scanning
    // body paragraph text (paragraph styles) and run text (character styles).
    let mut styleref_chars: HashSet<char> = HashSet::new();
    for para in &all_paras {
        if para.style_id.is_some() {
            for run in &para.runs {
                styleref_chars.extend(run.text.chars());
            }
        }
        for run in &para.runs {
            if run.char_style_id.is_some() {
                styleref_chars.extend(run.text.chars());
            }
        }
    }

    // Collect all page number formats across sections so inherited footers get
    // the right characters (e.g. footer in section 1 inherited by section 2 with lowerRoman).
    let all_page_num_formats: Vec<&str> = doc
        .sections
        .iter()
        .filter_map(|s| s.properties.page_num_format.as_deref())
        .collect();

    for section in &doc.sections {
        for hf in [
            &section.properties.header_default,
            &section.properties.header_first,
            &section.properties.header_even,
            &section.properties.footer_default,
            &section.properties.footer_first,
            &section.properties.footer_even,
        ]
        .into_iter()
        .flatten()
        {
            for para in hf_paragraphs(hf) {
                for run in &para.runs {
                    let key = font_key_buf(run, &mut key_buf);
                    let chars = used.entry(key.to_string()).or_default();
                    if run.caps || run.small_caps {
                        chars.extend(run.text.to_uppercase().chars());
                    } else {
                        chars.extend(run.text.chars());
                    }
                    if let Some(ref fc) = run.field_code {
                        match fc {
                            FieldCode::Page | FieldCode::NumPages | FieldCode::PageRef(_) => {
                                chars.extend('0'..='9');
                                for fmt in &all_page_num_formats {
                                    extend_chars_for_num_format(chars, fmt);
                                }
                            }
                            FieldCode::StyleRef(_) => {
                                chars.extend(styleref_chars.iter());
                            }
                        }
                    }
                }
            }
        }
    }

    // Collect characters for chart labels under the theme minor font
    {
        let mut chart_label_chars: HashSet<char> = HashSet::new();
        for para in &all_paras {
            if let Some(ref ic) = para.inline_chart {
                chart_label_chars.extend('0'..='9');
                chart_label_chars.insert('.');
                chart_label_chars.insert('-');
                chart_label_chars.insert(',');
                chart_label_chars.insert('%');
                for series in &ic.chart.series {
                    chart_label_chars.extend(series.label.chars());
                }
                if let Some(ref cat_axis) = ic.chart.cat_axis {
                    for label in &cat_axis.labels {
                        chart_label_chars.extend(label.chars());
                    }
                }
            }
        }
        if !chart_label_chars.is_empty() {
            used.entry(doc.chart_font_name.clone())
                .or_default()
                .extend(chart_label_chars);
        }
    }

    for chars in used.values_mut() {
        chars.insert(' ');
    }

    used
}

fn extend_chars_for_num_format(chars: &mut HashSet<char>, fmt: &str) {
    match fmt {
        "lowerRoman" => chars.extend(['i', 'v', 'x', 'l', 'c', 'd', 'm']),
        "upperRoman" => chars.extend(['I', 'V', 'X', 'L', 'C', 'D', 'M']),
        "lowerLetter" => chars.extend('a'..='z'),
        "upperLetter" => chars.extend('A'..='Z'),
        _ => {}
    }
}

/// Build a font key for SmartArt shapes, matching the `font_key_buf` format.
pub(super) fn smartart_font_key_str(name: &str, bold: bool, italic: bool) -> String {
    let mut key = crate::fonts::primary_font_name(name).to_string();
    match (bold, italic) {
        (true, true) => key.push_str("/BI"),
        (true, false) => key.push_str("/B"),
        (false, true) => key.push_str("/I"),
        (false, false) => {}
    }
    key
}

pub(super) fn collect_and_register_fonts(
    doc: &Document,
    pdf: &mut Pdf,
    alloc: &mut impl FnMut() -> Ref,
) -> (HashMap<String, FontEntry>, Vec<String>) {
    let mut seen_fonts: HashMap<String, FontEntry> = HashMap::new();
    let mut font_order: Vec<String> = Vec::new();
    let all_runs = collect_all_runs(doc);
    let mut used_chars_per_font = collect_used_chars(doc, &all_runs);

    for section in &doc.sections {
        for block in &section.blocks {
            if let Block::Paragraph(para) = block {
                for diagram in &para.smartart {
                    for shape in &diagram.shapes {
                        for sa_para in &shape.paragraphs {
                            for (i, run) in sa_para.runs.iter().enumerate() {
                                if let Some(ref name) = run.font_name {
                                    let key = smartart_font_key_str(name, run.bold, run.italic);
                                    let chars = used_chars_per_font.entry(key).or_default();
                                    chars.extend(run.text.chars());
                                    if i == 0 {
                                        if let Some(ref b) = sa_para.bullet {
                                            chars.extend(b.chars());
                                            chars.insert(' ');
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    let mut key_buf = String::new();

    for run in &all_runs {
        let key = font_key_buf(run, &mut key_buf);
        if !seen_fonts.contains_key(key) {
            let key_owned = key.to_string();
            let pdf_name = format!("F{}", font_order.len() + 1);
            let used = used_chars_per_font
                .get(&key_owned)
                .cloned()
                .unwrap_or_default();
            let entry = register_font(
                pdf,
                &run.font_name,
                run.bold,
                run.italic,
                pdf_name,
                alloc,
                &doc.embedded_fonts,
                &used,
                &doc.font_table,
            );
            font_order.push(key_owned.clone());
            seen_fonts.insert(key_owned, entry);
        }
    }

    for (key, used) in &used_chars_per_font {
        if seen_fonts.contains_key(key) {
            continue;
        }
        // SmartArt keys have style suffixes like /B, /I, /BI — extract the flags
        let (base, bold, italic) = if let Some((name, suffix)) = key.split_once('/') {
            let b = suffix.contains('B');
            let i = suffix.contains('I');
            (name, b, i)
        } else {
            (key.as_str(), false, false)
        };
        let pdf_name = format!("F{}", font_order.len() + 1);
        let entry = register_font(
            pdf, base, bold, italic, pdf_name, alloc,
            &doc.embedded_fonts, used, &doc.font_table,
        );
        seen_fonts.insert(key.clone(), entry);
        font_order.push(key.clone());
    }

    // Collect all CJK chars missing from their primary fonts and register a
    // shared CJK fallback font so the rendering code can substitute per-character.
    let mut all_missing_cjk: HashSet<char> = HashSet::new();
    for entry in seen_fonts.values() {
        all_missing_cjk.extend(&entry.missing_cjk_chars);
    }
    if !all_missing_cjk.is_empty() {
        let fallback_key = "__cjk_fallback".to_string();
        let pdf_name = format!("F{}", font_order.len() + 1);
        // Per-character fallback needs comprehensive CJK coverage (including
        // Japanese Kanji that Korean fonts like Malgun Gothic may lack).
        // Try comprehensive fonts first, then language-specific ones.
        #[cfg(target_os = "macos")]
        let fallback_font_name =
            "PMingLiU;MingLiU;Songti TC;Hiragino Sans GB;Hiragino Sans GB W3;Hiragino Sans W3;Hiragino Kaku Gothic ProN W3;Arial Unicode MS;Malgun Gothic";
        #[cfg(target_os = "linux")]
        let fallback_font_name = "Noto Sans CJK SC;Noto Sans CJK KR;Noto Sans CJK JP";
        #[cfg(target_os = "windows")]
        let fallback_font_name = "Yu Gothic;Microsoft YaHei;Malgun Gothic";
        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
        let fallback_font_name = "Arial Unicode MS";
        let entry = register_font(
            pdf,
            &fallback_font_name,
            false,
            false,
            pdf_name,
            alloc,
            &doc.embedded_fonts,
            &all_missing_cjk,
            &doc.font_table,
        );
        font_order.push(fallback_key.clone());
        seen_fonts.insert(fallback_key, entry);

        // Copy fallback char widths into each primary font so layout uses correct widths
        if let Some(fb_widths) = seen_fonts
            .get("__cjk_fallback")
            .and_then(|e| e.char_widths_1000.clone())
        {
            for entry in seen_fonts.values_mut() {
                if entry.missing_cjk_chars.is_empty() {
                    continue;
                }
                let widths = entry.char_widths_1000.get_or_insert_with(HashMap::new);
                for &ch in &entry.missing_cjk_chars {
                    if let Some(&w) = fb_widths.get(&ch) {
                        widths.insert(ch, w);
                    }
                }
            }
        }
    }

    if seen_fonts.is_empty() {
        let pdf_name = "F1".to_string();
        let entry = register_font(
            pdf,
            "Helvetica",
            false,
            false,
            pdf_name,
            alloc,
            &doc.embedded_fonts,
            &HashSet::new(),
            &doc.font_table,
        );
        seen_fonts.insert("Helvetica".to_string(), entry);
        font_order.push("Helvetica".to_string());
    }

    (seen_fonts, font_order)
}