Skip to main content

fonts/
fonts.rs

1//! Per-font glyph coverage: `cargo run --example fonts -- file.pdf`.
2//!
3//! Reports, for every font on the page, how many of its glyphs produced no text at all. A glyph
4//! with no text is invisible to every downstream consumer, so a font with a high unmapped rate
5//! is the single most useful thing to know when text is missing — and mathematics fonts are
6//! where it usually happens, because TeX's are symbolic, often carry no `/ToUnicode`, and use
7//! glyph names no standard encoding lists.
8
9use std::collections::BTreeMap;
10
11#[derive(Default)]
12struct Tally {
13    total: usize,
14    unmapped: usize,
15    flags: u32,
16    sample: Vec<u32>,
17}
18
19fn main() {
20    let mut args = std::env::args().skip(1);
21    let Some(path) = args.next() else {
22        eprintln!("usage: fonts <file.pdf>");
23        std::process::exit(2);
24    };
25    let doc = match rustium_pdf::Document::open(&path) {
26        Ok(d) => d,
27        Err(e) => {
28            eprintln!("{path}: {e}");
29            std::process::exit(1);
30        }
31    };
32
33    let mut fonts: BTreeMap<String, Tally> = BTreeMap::new();
34    for i in 0..doc.page_count() {
35        let Ok(page) = doc.page(i) else { continue };
36        for g in page.glyphs.iter().filter(|g| !g.is_generated_space) {
37            let t = fonts.entry(g.base_font.clone()).or_default();
38            t.total += 1;
39            t.flags = g.flags.0;
40            if g.text.is_empty() {
41                t.unmapped += 1;
42                if t.sample.len() < 12 {
43                    t.sample.push(g.code());
44                }
45            }
46        }
47    }
48
49    let (mut total, mut unmapped) = (0usize, 0usize);
50    println!(
51        "{:<40} {:>8} {:>9}  unmapped codes",
52        "font", "glyphs", "unmapped"
53    );
54    println!("{}", "-".repeat(96));
55    for (name, t) in &fonts {
56        total += t.total;
57        unmapped += t.unmapped;
58        let pct = if t.total > 0 {
59            t.unmapped as f32 * 100.0 / t.total as f32
60        } else {
61            0.0
62        };
63        let codes: Vec<String> = t.sample.iter().map(|c| format!("{c:#04x}")).collect();
64        let marker = if pct > 5.0 { " <<<" } else { "" };
65        println!(
66            "{:<40} {:>8} {:>7.1}%  {}{}",
67            name.chars().take(40).collect::<String>(),
68            t.total,
69            pct,
70            codes.join(" "),
71            marker
72        );
73    }
74    println!("{}", "-".repeat(96));
75    let pct = if total > 0 {
76        unmapped as f32 * 100.0 / total as f32
77    } else {
78        0.0
79    };
80    println!("{:<40} {:>8} {:>7.1}%", "TOTAL", total, pct);
81}