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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
mod cache;
mod discovery;
mod embed;
mod encoding;

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::Instant;

use pdf_writer::{Name, Pdf, Ref};

use crate::model::{FontFamily, FontTable, Run};

pub(crate) use encoding::{encode_as_gids, to_winansi_bytes};

/// Metrics extracted from a font file during embedding. Does not include font resolution
/// metadata (path, face index, synthetic bold) which is tracked separately.
pub(crate) struct FontMetrics {
    pub(crate) widths_1000: Vec<f32>,
    pub(crate) line_h_ratio: f32,
    pub(crate) ascender_ratio: f32,
    /// sTypo-based line ratio — Word's basis for docGrid cell counting.
    pub(crate) typo_line_ratio: Option<f32>,
    pub(crate) char_to_gid: HashMap<char, u16>,
    pub(crate) char_widths_1000: HashMap<char, f32>,
    pub(crate) kern_pairs: HashMap<(u16, u16), f32>,
}

/// Font metrics bundled with resolution metadata from the font discovery phase.
struct ResolvedFont {
    metrics: FontMetrics,
    synthetic_bold: bool,
    font_path: Option<PathBuf>,
    face_index: u32,
}

pub(crate) struct FontEntry {
    pub(crate) pdf_name: String,
    pub(crate) font_ref: Ref,
    pub(crate) widths_1000: Vec<f32>,
    pub(crate) line_h_ratio: Option<f32>,
    pub(crate) ascender_ratio: Option<f32>,
    /// sTypo-based line ratio — Word's basis for docGrid cell counting.
    pub(crate) typo_line_ratio: Option<f32>,
    pub(crate) char_to_gid: Option<HashMap<char, u16>>,
    pub(crate) char_widths_1000: Option<HashMap<char, f32>>,
    pub(crate) kern_pairs: Option<HashMap<(u16, u16), f32>>,
    pub(crate) synthetic_bold: bool,
    /// True when the requested font was missing and a metric-changing fallback
    /// (CJK/family/standard-14) was used — altName/alias mappings don't count.
    pub(crate) is_substituted: bool,
    /// CJK chars requested but not present in this font (need fallback rendering).
    pub(crate) missing_cjk_chars: HashSet<char>,
    /// Font file path for glyph outline extraction (text warping).
    pub(crate) font_path: Option<PathBuf>,
    pub(crate) face_index: u32,
}

impl FontEntry {
    /// Width of a single character in 1000-units. Uses the per-char cache (covers
    /// all Unicode chars seen in the document), falls back to the WinAnsi table.
    pub(crate) fn char_width_1000(&self, ch: char) -> f32 {
        if let Some(w) = self.char_widths_1000.as_ref().and_then(|m| m.get(&ch)) {
            return *w;
        }
        let byte = encoding::char_to_winansi(ch);
        if byte >= 32 {
            self.widths_1000[(byte - 32) as usize]
        } else {
            0.0
        }
    }

    /// Encode text for a PDF show operator: glyph IDs when this font carries a
    /// char→gid map (embedded subset), else WinAnsi bytes (standard font).
    pub(crate) fn encode(&self, text: &str) -> Vec<u8> {
        match &self.char_to_gid {
            Some(map) => encoding::encode_as_gids(text, map),
            None => encoding::to_winansi_bytes(text),
        }
    }

    pub(crate) fn word_width(&self, word: &str, font_size: f32, kern: bool) -> f32 {
        if !kern || self.kern_pairs.is_none() {
            return word
                .chars()
                .map(|ch| self.char_width_1000(ch) * font_size / 1000.0)
                .sum();
        }
        let scale = font_size / 1000.0;
        let mut prev: Option<char> = None;
        let mut w = 0.0;
        for ch in word.chars() {
            if let Some(p) = prev {
                w += self.kern_1000(p, ch) * scale;
            }
            w += self.char_width_1000(ch) * scale;
            prev = Some(ch);
        }
        w
    }

    fn kern_1000(&self, left: char, right: char) -> f32 {
        let (Some(pairs), Some(c2g)) = (&self.kern_pairs, &self.char_to_gid) else {
            return 0.0;
        };
        c2g.get(&left)
            .zip(c2g.get(&right))
            .and_then(|(&l, &r)| pairs.get(&(l, r)))
            .copied()
            .unwrap_or(0.0)
    }

    pub(crate) fn space_width(&self, font_size: f32) -> f32 {
        self.char_width_1000(' ') * font_size / 1000.0
    }
}

pub(crate) fn primary_font_name(name: &str) -> &str {
    name.split(';').next().unwrap_or(name).trim()
}

/// Write the font key for a run into the provided buffer, returning it as a `&str`.
/// Avoids per-call heap allocation when callers reuse the buffer.
pub(crate) fn font_key_buf<'a>(run: &Run, buf: &'a mut String) -> &'a str {
    buf.clear();
    buf.push_str(primary_font_name(&run.font_name));
    match (run.bold, run.italic) {
        (true, true) => buf.push_str("/BI"),
        (true, false) => buf.push_str("/B"),
        (false, true) => buf.push_str("/I"),
        (false, false) => {}
    }
    buf.as_str()
}

pub(crate) fn font_key(run: &Run) -> String {
    let mut buf = String::new();
    font_key_buf(run, &mut buf);
    buf
}

pub(crate) type EmbeddedFonts = HashMap<(String, bool, bool), Vec<u8>>;

fn try_font(
    pdf: &mut Pdf,
    candidate: &str,
    bold: bool,
    italic: bool,
    font_ref: Ref,
    descriptor_ref: Ref,
    data_ref: Ref,
    alloc: &mut impl FnMut() -> Ref,
    embedded_fonts: &EmbeddedFonts,
    used_chars: &HashSet<char>,
) -> Option<ResolvedFont> {
    let mut embed = |data: &[u8], face_index: u32| {
        embed::embed_truetype(
            pdf,
            font_ref,
            descriptor_ref,
            data_ref,
            candidate,
            data,
            face_index,
            used_chars,
            alloc,
        )
    };

    let embedded_key = (candidate.to_lowercase(), bold, italic);
    if let Some(metrics) = embedded_fonts.get(&embedded_key).and_then(|d| embed(d, 0)) {
        return Some(ResolvedFont {
            metrics,
            synthetic_bold: false,
            font_path: None,
            face_index: 0,
        });
    }

    let (path, face_index, exact_match) = discovery::find_font_file(candidate, bold, italic)?;
    let data = std::fs::read(&path).ok()?;
    let metrics = embed(&data, face_index)?;
    Some(ResolvedFont {
        metrics,
        synthetic_bold: bold && !exact_match,
        font_path: Some(path),
        face_index,
    })
}

fn lookup_font_table<'a>(
    font_table: &'a FontTable,
    name: &str,
) -> Option<&'a crate::model::FontTableEntry> {
    font_table.get(name).or_else(|| {
        let lower = name.to_lowercase();
        font_table
            .iter()
            .find(|(k, _)| k.to_lowercase() == lower)
            .map(|(_, v)| v)
    })
}

fn family_fallback(family: FontFamily) -> Option<&'static str> {
    match family {
        FontFamily::Roman => Some("Times New Roman"),
        FontFamily::Swiss => Some("Arial"),
        FontFamily::Modern => Some("Courier New"),
        FontFamily::Script | FontFamily::Decorative => Some("Times New Roman"),
        // `w:family="auto"` (unspecified) — substitute a real vendored sans
        // instead of dropping to the base-14 Helvetica last resort, which matches
        // Word's output poorly. INTERIM choice: Arial. NOTE: for the known case
        // (Bosch Office Sans missing) Word's own PDF export actually substitutes
        // Calibri, not Arial — so Calibri may be the better universal default, or
        // the right rule may be panose/theme-based. Left as Arial pending a survey
        // of what Word substitutes across multiple missing-font fixtures.
        FontFamily::Auto => Some("Arial"),
    }
}

/// True if the face declares itself a script/handwriting design
/// (OS/2 sFamilyClass class 10, or PANOSE family kind 3 "Latin Script").
fn face_is_script_design(path: &std::path::Path, face_index: u32) -> bool {
    let Ok(data) = std::fs::read(path) else {
        return false;
    };
    let Ok(face) = ttf_parser::Face::parse(&data, face_index) else {
        return false;
    };
    let Some(os2) = face.raw_face().table(ttf_parser::Tag::from_bytes(b"OS/2")) else {
        return false;
    };
    // sFamilyClass high byte at offset 30, PANOSE bFamilyType at offset 32
    os2.get(30) == Some(&10) || os2.get(32) == Some(&3)
}

fn known_font_alias(name: &str) -> Option<&'static str> {
    match name {
        "Palatino Linotype" => Some("Palatino"),
        "標楷體" | "DFKai-SB" => Some("BiauKai"),
        _ => None,
    }
}

fn has_cjk_chars(chars: &HashSet<char>) -> bool {
    chars.iter().any(|&c| crate::docx::is_east_asian_char(c))
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum CjkScript {
    Unknown,
    SimplifiedChinese,
    TraditionalChinese,
    Japanese,
    Korean,
}

/// Guess the script from the primary font name so we can order the CJK
/// fallback list to favor a font with matching metrics.
pub(crate) fn classify_cjk_script(primary: &str) -> CjkScript {
    // Simplified-Chinese family names (宋体/仿宋/黑体/楷体 + 华文 variants).
    const SC_HINTS: &[&str] = &[
        "宋体", "仿宋", "黑体", "楷体", "华文", "微软雅黑", "方正",
        "SimSun", "SimHei", "FangSong", "KaiTi", "Microsoft YaHei",
        "STSong", "STFangsong", "STKaiti", "STHeiti", "STZhongsong",
    ];
    // Traditional-Chinese hints.
    const TC_HINTS: &[&str] = &[
        "細明體", "新細明體", "標楷體", "微軟正黑體", "華康",
        "PMingLiU", "MingLiU", "DFKai-SB", "Microsoft JhengHei",
    ];
    // Japanese hints (kanji/kana forms + common font names).
    const JA_HINTS: &[&str] = &[
        "明朝", "ゴシック", "メイリオ", "游明朝", "游ゴシック",
        "MS明朝", "MS ゴシック", "MS P明朝", "MS Pゴシック",
        "MS Mincho", "MS Gothic", "MS PMincho", "MS PGothic",
        "Meiryo", "Yu Mincho", "Yu Gothic", "Hiragino",
    ];
    // Korean hints.
    const KO_HINTS: &[&str] = &[
        "바탕", "돋움", "굴림", "궁서", "맑은 고딕", "나눔",
        "Batang", "Dotum", "Gulim", "Gungsuh", "Malgun Gothic", "Nanum",
    ];

    for h in SC_HINTS {
        if primary.contains(h) {
            return CjkScript::SimplifiedChinese;
        }
    }
    for h in TC_HINTS {
        if primary.contains(h) {
            return CjkScript::TraditionalChinese;
        }
    }
    for h in JA_HINTS {
        if primary.contains(h) {
            return CjkScript::Japanese;
        }
    }
    for h in KO_HINTS {
        if primary.contains(h) {
            return CjkScript::Korean;
        }
    }
    CjkScript::Unknown
}

pub(crate) fn cjk_fallback_fonts_for_script(script: CjkScript) -> &'static [&'static str] {
    #[cfg(target_os = "macos")]
    {
        match script {
            CjkScript::SimplifiedChinese => &[
                "Hiragino Sans GB",
                "Hiragino Sans GB W3",
                "PingFang SC",
                "Songti SC",
                "Malgun Gothic",
                "PMingLiU",
                "Arial Unicode MS",
            ],
            CjkScript::TraditionalChinese => &[
                "PMingLiU",
                "MingLiU",
                "Songti TC",
                "Malgun Gothic",
                "Hiragino Sans GB",
                "Arial Unicode MS",
            ],
            CjkScript::Japanese => &[
                "Hiragino Kaku Gothic ProN W3",
                "Hiragino Sans W3",
                "Yu Gothic",
                "Malgun Gothic",
                "Arial Unicode MS",
                "Hiragino Sans GB",
            ],
            CjkScript::Korean => &[
                "Malgun Gothic",
                "AppleSD Gothic Neo",
                "Apple SD Gothic Neo",
                "Hiragino Sans GB",
                "Arial Unicode MS",
            ],
            CjkScript::Unknown => &[
                "Malgun Gothic",
                "Hiragino Sans GB",
                "Hiragino Sans GB W3",
                "PMingLiU",
                "MingLiU",
                "Songti TC",
                "AppleSD Gothic Neo",
                "Apple SD Gothic Neo",
                "Hiragino Sans W3",
                "Hiragino Kaku Gothic ProN W3",
                "Arial Unicode MS",
                "PingFang SC",
            ],
        }
    }
    #[cfg(target_os = "linux")]
    {
        let _ = script;
        &[
            "Noto Sans CJK SC",
            "Noto Sans CJK KR",
            "Noto Sans CJK JP",
        ]
    }
    #[cfg(target_os = "windows")]
    {
        let _ = script;
        &[
            "Malgun Gothic",
            "Yu Gothic",
            "Microsoft YaHei",
        ]
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        let _ = script;
        &[]
    }
}

pub(crate) fn register_font(
    pdf: &mut Pdf,
    font_name: &str,
    bold: bool,
    italic: bool,
    pdf_name: String,
    alloc: &mut impl FnMut() -> Ref,
    embedded_fonts: &EmbeddedFonts,
    used_chars: &HashSet<char>,
    font_table: &FontTable,
) -> FontEntry {
    let t0 = Instant::now();
    let font_ref = alloc();
    let descriptor_ref = alloc();
    let data_ref = alloc();

    let primary = primary_font_name(font_name);

    let mut try_candidate = |name: &str| {
        try_font(
            pdf,
            name,
            bold,
            italic,
            font_ref,
            descriptor_ref,
            data_ref,
            alloc,
            embedded_fonts,
            used_chars,
        )
    };

    let needs_cjk = has_cjk_chars(used_chars);
    let table_entry = lookup_font_table(font_table, primary);

    let script = classify_cjk_script(primary);
    let substituted = std::cell::Cell::new(false);
    let try_cjk_fallback = |tc: &mut dyn FnMut(&str) -> Option<ResolvedFont>| {
        cjk_fallback_fonts_for_script(script).iter().find_map(|cjk_font| {
            log::debug!("Trying CJK fallback \"{cjk_font}\" for \"{primary}\"");
            let m = tc(cjk_font)?;
            log::info!("Font substitution: {primary} → CJK fallback \"{cjk_font}\"");
            substituted.set(true);
            Some(m)
        })
    };

    // If the fontTable provides an altName, try it first — it's the document's
    // explicit mapping and more reliable than the system font index (which may
    // resolve a localized name like "바탕" to a different font than "Batang").
    // Math fonts are excluded: an altName like "Cambria Math" (seen for
    // "Korinna BT") has enormous win ascent/descent metrics that balloon every
    // line; Word substitutes body text with a normal family fallback instead.
    let result = table_entry
        .and_then(|entry| {
            let alt = entry.alt_name.as_ref()?;
            // "SignPainter-HouseScript": Word-for-Mac writes this cursive face as
            // altName for fonts missing on the authoring machine (e.g. Merriweather);
            // it never reflects what the reference render used.
            if alt.contains("Math") || alt == "SignPainter-HouseScript" {
                return None;
            }
            let m = try_candidate(alt)?;
            // Reject a script/handwriting altName for a non-script family: Word on
            // macOS records whatever it substituted on screen (e.g. Merriweather →
            // SignPainter-HouseScript), but the reference machine had the real font.
            // A cursive body face is always worse than the family fallback.
            if entry.family != crate::model::FontFamily::Script
                && m.font_path
                    .as_deref()
                    .is_some_and(|p| face_is_script_design(p, m.face_index))
            {
                log::info!("Rejecting script-classified altName \"{alt}\" for {primary}");
                return None;
            }
            log::info!("Font substitution: {primary} → altName \"{alt}\"");
            Some(m)
        })
        .or_else(|| {
            font_name
                .split(';')
                .map(|s| s.trim())
                .find_map(|c| try_candidate(c))
        })
        .or_else(|| {
            let alias = known_font_alias(primary)?;
            let m = try_candidate(alias)?;
            log::info!("Font substitution: {primary} → alias \"{alias}\"");
            Some(m)
        })
        .or_else(|| {
            let entry = table_entry?;
            // Try CJK fallback before family fallback — family fonts (TNR, Courier)
            // lack CJK glyphs and would produce squares
            if needs_cjk {
                if let Some(m) = try_cjk_fallback(&mut try_candidate) {
                    return Some(m);
                }
            }
            let fallback = family_fallback(entry.family)?;
            let m = try_candidate(fallback)?;
            log::info!(
                "Font substitution: {primary} → family {:?} fallback \"{fallback}\"",
                entry.family
            );
            substituted.set(true);
            Some(m)
        })
        .or_else(|| {
            if !needs_cjk {
                return None;
            }
            try_cjk_fallback(&mut try_candidate)
        });

    // Compute which CJK chars are missing from the resolved font
    let missing_cjk = if needs_cjk {
        let covered: HashSet<char> = result
            .as_ref()
            .map(|r| r.metrics.char_to_gid.keys().copied().collect())
            .unwrap_or_default();
        used_chars
            .iter()
            .copied()
            .filter(|ch| !covered.contains(ch) && crate::docx::is_east_asian_char(*ch))
            .collect()
    } else {
        HashSet::new()
    };

    let entry = match result {
        Some(r) => FontEntry {
            pdf_name,
            font_ref,
            widths_1000: r.metrics.widths_1000,
            line_h_ratio: Some(r.metrics.line_h_ratio),
            ascender_ratio: Some(r.metrics.ascender_ratio),
            typo_line_ratio: r.metrics.typo_line_ratio,
            char_to_gid: Some(r.metrics.char_to_gid),
            char_widths_1000: Some(r.metrics.char_widths_1000),
            kern_pairs: if r.metrics.kern_pairs.is_empty() {
                None
            } else {
                Some(r.metrics.kern_pairs)
            },
            synthetic_bold: r.synthetic_bold,
            is_substituted: substituted.get(),
            missing_cjk_chars: missing_cjk,
            font_path: r.font_path,
            face_index: r.face_index,
        },
        None => {
            // Pick the matching standard-14 Helvetica variant so a bold/italic run of an
            // unresolved font still renders bold/italic. Previously this always emitted plain
            // Helvetica, dropping the weight for every unresolved font across the corpus.
            let base_font: &[u8] = match (bold, italic) {
                (true, true) => b"Helvetica-BoldOblique",
                (true, false) => b"Helvetica-Bold",
                (false, true) => b"Helvetica-Oblique",
                (false, false) => b"Helvetica",
            };
            log::warn!(
                "Font not found: {font_name} bold={bold} italic={italic} — using {}",
                String::from_utf8_lossy(base_font)
            );
            pdf.type1_font(font_ref)
                .base_font(Name(base_font))
                .encoding_predefined(Name(b"WinAnsiEncoding"));
            FontEntry {
                pdf_name,
                font_ref,
                widths_1000: encoding::helvetica_widths(),
                line_h_ratio: None,
                ascender_ratio: None,
                typo_line_ratio: None,
                char_to_gid: None,
                char_widths_1000: None,
                kern_pairs: None,
                synthetic_bold: false,
                is_substituted: true,
                missing_cjk_chars: missing_cjk,
                font_path: None,
                face_index: 0,
            }
        }
    };

    log::debug!(
        "register_font: {font_name} bold={bold} italic={italic} → {:.1}ms",
        t0.elapsed().as_secs_f64() * 1000.0,
    );

    entry
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_primary_font_name_simple() {
        assert_eq!(primary_font_name("Arial"), "Arial");
        assert_eq!(primary_font_name("Times New Roman"), "Times New Roman");
    }

    #[test]
    fn test_primary_font_name_with_fallback() {
        assert_eq!(primary_font_name("Arial; Helvetica"), "Arial");
        assert_eq!(primary_font_name("Calibri; sans-serif"), "Calibri");
    }

    #[test]
    fn test_primary_font_name_with_whitespace() {
        assert_eq!(primary_font_name("  Arial  ; Helvetica"), "Arial");
    }

    #[test]
    fn test_primary_font_name_empty() {
        assert_eq!(primary_font_name(""), "");
    }

    fn make_run(font: &str, bold: bool, italic: bool) -> Run {
        Run {
            font_name: font.to_string(),
            font_size: 12.0,
            bold,
            italic,
            text_scale: 100.0,
            ..Run::default()
        }
    }

    #[test]
    fn test_font_key_regular() {
        let run = make_run("Arial", false, false);
        let mut buf = String::new();
        assert_eq!(font_key_buf(&run, &mut buf), "Arial");
    }

    #[test]
    fn test_font_key_bold() {
        let run = make_run("Arial", true, false);
        let mut buf = String::new();
        assert_eq!(font_key_buf(&run, &mut buf), "Arial/B");
    }

    #[test]
    fn test_font_key_italic() {
        let run = make_run("Arial", false, true);
        let mut buf = String::new();
        assert_eq!(font_key_buf(&run, &mut buf), "Arial/I");
    }

    #[test]
    fn test_font_key_bold_italic() {
        let run = make_run("Arial", true, true);
        let mut buf = String::new();
        assert_eq!(font_key_buf(&run, &mut buf), "Arial/BI");
    }

    #[test]
    fn test_font_key_with_fallback_font() {
        let run = make_run("Calibri; sans-serif", false, false);
        let mut buf = String::new();
        assert_eq!(font_key_buf(&run, &mut buf), "Calibri");
    }
}