pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
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
654
655
656
657
658
659
//! `pdfsift dump`: prints the raw primitives PDFium extracts, in content-stream order.
//!
//! Coordinates are in PDF points (1/72 inch) with the origin at the TOP-left of the page
//! (PDF itself uses bottom-left; we flip y so that reading top-to-bottom is natural).

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Context, Result, bail};
use pdfium_render::prelude::*;

use crate::{engine, tags};

pub struct Options {
    /// 0-based page indices; None = all.
    pub pages: Option<Vec<PdfPageIndex>>,
    pub paths: bool,
    pub tags: bool,
    /// Print the character level (`PdfPageText::chars()`) after the objects.
    pub chars: bool,
    /// Restrict `--chars` to this region (top-origin points).
    pub region: Option<Region>,
    /// Show marked-content marks (name and params such as MCID, ActualText, Alt, E) per
    /// object, a per-page summary of ActualText/Alt/E values, and, with `chars`, the object
    /// and ActualText each char comes from.
    pub marks: bool,
}

/// Axis-aligned rectangle in the dump's coordinates: x from the left, y from the TOP.
#[derive(Clone, Copy, Debug)]
pub struct Region {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
}

impl Region {
    fn contains(&self, x: f32, y: f32) -> bool {
        x >= self.x && x <= self.x + self.w && y >= self.y && y <= self.y + self.h
    }
}

/// Parses `x,y,w,h` (points, y measured from the top of the page).
pub fn parse_region(spec: Option<&str>) -> Result<Option<Region>> {
    let Some(spec) = spec else { return Ok(None) };
    let v: Vec<f32> = spec
        .split(',')
        .map(|p| p.trim().parse::<f32>())
        .collect::<Result<_, _>>()
        .with_context(|| format!("invalid region {spec:?}: expected x,y,w,h in points"))?;
    match v[..] {
        [x, y, w, h] if w > 0.0 && h > 0.0 && v.iter().all(|n| n.is_finite()) => {
            Ok(Some(Region { x, y, w, h }))
        }
        _ => bail!("invalid region {spec:?}: expected x,y,w,h with w > 0 and h > 0"),
    }
}

pub fn parse_pages(spec: Option<&str>) -> Result<Option<Vec<PdfPageIndex>>> {
    let Some(spec) = spec else { return Ok(None) };
    let mut out = Vec::new();
    for part in spec.split(',') {
        let (a, b) = match part.split_once('-') {
            Some((a, b)) => (
                a.trim().parse::<PdfPageIndex>()?,
                b.trim().parse::<PdfPageIndex>()?,
            ),
            None => {
                let n = part.trim().parse::<PdfPageIndex>()?;
                (n, n)
            }
        };
        if a < 1 || b < a {
            bail!("invalid page range: {part}");
        }
        out.extend((a - 1)..b);
    }
    Ok(Some(out))
}

pub fn run(file: &Path, opts: &Options) -> Result<()> {
    let pdfium = engine::load()?;
    let doc = pdfium
        .load_pdf_from_file(file, None)
        .with_context(|| format!("cannot open {}", file.display()))?;
    let raw = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());

    // ---- document ----
    outln!("== document: {}", file.display());
    outln!("version:  {:?}", doc.version());
    outln!("pages:    {}", doc.pages().len());
    for (label, tag) in [
        ("title", PdfDocumentMetadataTagType::Title),
        ("author", PdfDocumentMetadataTagType::Author),
        ("creator", PdfDocumentMetadataTagType::Creator),
        ("producer", PdfDocumentMetadataTagType::Producer),
    ] {
        if let Some(t) = doc.metadata().get(tag) {
            outln!("{label:<9} {:?}", t.value());
        }
    }
    let tagged = raw.as_ref().map(|r| r.is_tagged());
    outln!(
        "tagged:   {}",
        tagged.map_or("unknown".into(), |t| t.to_string())
    );

    outln!("outline:");
    match doc.bookmarks().root() {
        Some(root) => print_bookmarks(&root, 1),
        None => outln!("  (none)"),
    }

    // ---- pages ----
    let indices: Vec<PdfPageIndex> = match &opts.pages {
        Some(p) => p.clone(),
        None => (0..doc.pages().len()).collect(),
    };
    for idx in indices {
        let page = match doc.pages().get(idx) {
            Ok(p) => p,
            Err(_) => {
                outln!("\n== page {} does not exist", idx + 1);
                continue;
            }
        };
        let raw_page = raw.as_ref().and_then(|r| r.page(idx));
        dump_page(&page, idx, raw_page.as_ref(), opts);
    }
    Ok(())
}

fn print_bookmarks(first: &PdfBookmark, depth: usize) {
    // iter_siblings() does not include the node itself.
    for bm in std::iter::once(first.clone()).chain(first.iter_siblings()) {
        let page = bm
            .destination()
            .and_then(|d| d.page_index().ok())
            .map_or("?".to_string(), |i| (i + 1).to_string());
        outln!(
            "{}- {:?} (p{page})",
            "  ".repeat(depth),
            bm.title().unwrap_or_default()
        );
        if let Some(child) = bm.first_child() {
            print_bookmarks(&child, depth + 1);
        }
    }
}

struct Ctx<'a> {
    page_h: f32,
    opts: &'a Options,
    path_count: usize,
    path_area: BTreeMap<&'static str, usize>,
    /// (mark name, param key, value) -> count, for the `--marks` summary.
    mark_values: BTreeMap<(String, String, String), usize>,
}

fn dump_page(page: &PdfPage, idx: PdfPageIndex, raw: Option<&tags::RawPage>, opts: &Options) {
    let (w, h) = (page.width().value, page.height().value);
    let rot = page
        .rotation()
        .map(|r| format!("{r:?}"))
        .unwrap_or_default();
    outln!("\n== page {} ({w:.0} x {h:.0} pt, rotation {rot})", idx + 1);

    let mcids = raw.map(|r| r.object_mcids()).unwrap_or_default();
    let marks = if opts.marks {
        raw.map(|r| r.object_marks()).unwrap_or_default()
    } else {
        Vec::new()
    };
    let mut ctx = Ctx {
        mark_values: BTreeMap::new(),
        page_h: h,
        opts,
        path_count: 0,
        path_area: BTreeMap::new(),
    };

    outln!("-- objects (content-stream order; y measured from top)");
    for (i, obj) in page.objects().iter().enumerate() {
        let mcid = mcids.get(i).copied().filter(|m| *m >= 0);
        dump_object(&obj, &format!("{i:>4}"), 0, mcid, marks.get(i), &mut ctx);
    }
    if !opts.paths && ctx.path_count > 0 {
        let sizes: Vec<String> = ctx
            .path_area
            .iter()
            .map(|(k, v)| format!("{v} {k}"))
            .collect();
        outln!(
            "     paths: {} total ({})  [use --paths to list]",
            ctx.path_count,
            sizes.join(", ")
        );
    }
    if opts.marks && !ctx.mark_values.is_empty() {
        outln!(
            "-- marked-content text params (objects, incl. form children; mark/key = value: count)"
        );
        for ((name, key, value), n) in &ctx.mark_values {
            outln!("     {name}/{key} = {value}: {n}");
        }
    }

    let links: Vec<_> = page.links().iter().collect();
    if !links.is_empty() {
        outln!("-- links");
        for link in links {
            let target = link
                .action()
                .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
                .or_else(|| {
                    link.destination()
                        .and_then(|d| d.page_index().ok())
                        .map(|p| format!("page {}", p + 1))
                })
                .unwrap_or_else(|| "?".into());
            let r = link.rect().map(|r| fmt_rect(&r, h)).unwrap_or_default();
            outln!("     {r}  -> {target}");
        }
    }

    if opts.chars {
        let char_marks = if opts.marks {
            raw.map(|r| (r.char_objects(), &marks))
        } else {
            None
        };
        dump_chars(page, h, opts.region, char_marks);
    }

    if opts.tags {
        if let Some(raw) = raw {
            let tree = raw.structure();
            if !tree.is_empty() {
                outln!("-- structure tree");
                for e in &tree {
                    print_elem(e, 1);
                }
            }
        }
    }
}

fn dump_object(
    obj: &PdfPageObject,
    id: &str,
    depth: usize,
    mcid: Option<i32>,
    marks: Option<&tags::ObjMarks>,
    ctx: &mut Ctx,
) {
    let indent = "  ".repeat(depth);
    let bbox = obj
        .bounds()
        .map(|q| fmt_rect(&q.to_rect(), ctx.page_h))
        .unwrap_or_default();
    let mut mc = mcid.map(|m| format!(" mcid={m}")).unwrap_or_default();
    if let Some(m) = marks.filter(|m| !m.marks.is_empty()) {
        mc.push_str(&format!(" marks=[{}]", fmt_marks(&m.marks)));
        for mark in &m.marks {
            for key in TEXT_PARAMS {
                if let Some(v) = mark.str_param(key) {
                    *ctx.mark_values
                        .entry((mark.name.clone(), key.to_string(), format!("{v:?}")))
                        .or_default() += 1;
                }
            }
        }
    }

    match obj.object_type() {
        PdfPageObjectType::Text => {
            let t = obj.as_text_object().unwrap();
            let font = t.font();
            let weight = font.weight().ok().map(weight_value);
            let name = font.name();
            let mut flags = Vec::new();
            if font.is_bold_reenforced() || name.contains("Bold") {
                flags.push("bold");
            }
            if font.is_italic() || name.contains("Italic") || name.contains("Oblique") {
                flags.push("italic");
            }
            if font.is_fixed_pitch() {
                flags.push("mono");
            }
            let mode = t.render_mode();
            let mode = if matches!(mode, PdfPageTextRenderMode::FilledUnstroked) {
                String::new()
            } else {
                format!(" mode={mode:?}")
            };
            outln!(
                "{id} {indent}T {bbox}  {:.1}pt w{} {:?}{}{mode}{mc}  {:?}",
                t.scaled_font_size().value,
                weight.map_or("?".into(), |w| w.to_string()),
                name,
                if flags.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", flags.join(","))
                },
                truncate(&t.text(), 240),
            );
        }
        PdfPageObjectType::Image => {
            let img = obj.as_image_object().unwrap();
            let px = match (img.width(), img.height()) {
                (Ok(w), Ok(h)) => format!("{w}x{h}px"),
                _ => "?px".into(),
            };
            let filters: Vec<String> = img.filters().iter().map(|f| f.name().to_string()).collect();
            let cs = img
                .color_space()
                .map(|c| format!("{c:?}"))
                .unwrap_or_default();
            let bpp = img
                .bits_per_pixel()
                .map(|b| b.to_string())
                .unwrap_or_default();
            outln!(
                "{id} {indent}I {bbox}  {px} filters=[{}] colorspace={cs} bpp={bpp}{mc}",
                filters.join(",")
            );
        }
        PdfPageObjectType::Path => {
            ctx.path_count += 1;
            if ctx.opts.paths {
                outln!("{id} {indent}P {bbox}{mc}");
            } else if let Ok(q) = obj.bounds() {
                let r = q.to_rect();
                let (w, h) = (r.width().value, r.height().value);
                let kind = if w < 1.5 || h < 1.5 {
                    "line-like"
                } else if w * h < 400.0 {
                    "small"
                } else {
                    "large"
                };
                *ctx.path_area.entry(kind).or_default() += 1;
            }
        }
        PdfPageObjectType::XObjectForm => {
            let form = obj.as_x_object_form_object().unwrap();
            outln!(
                "{id} {indent}F {bbox}  form xobject, {} objects{mc}",
                form.len()
            );
            for (j, child) in form.iter().enumerate() {
                let child_marks = marks.and_then(|m| m.children.get(j));
                dump_object(
                    &child,
                    &format!("{id}.{j}"),
                    depth + 1,
                    None,
                    child_marks,
                    ctx,
                );
            }
        }
        other => outln!("{id} {indent}? {bbox}  {other:?}{mc}"),
    }
}

/// Same-baseline tolerance for the gap column, relative to font size. Baselines of chars in
/// one line differ only by float noise unless there is a super/subscript (footnote calls are
/// raised by ~0.3 size, see achado 001), so 0.1 keeps those out of the gap computation.
const SAME_BASELINE_TOL: f32 = 0.1;

/// Last real (non-generated) char seen, for gap computation.
struct PrevChar {
    baseline: f32,
    loose_right: f32,
    tight_right: f32,
}

/// Prints one line per character of the page text layer.
///
/// Bounds: `loose` comes from FPDFText_GetLooseCharBox (glyph advance width horizontally,
/// font ascent/descent vertically), so loose boxes of consecutive glyphs touch when the
/// producer adds no extra spacing. `tight` comes from FPDFText_GetCharBox (the ink box of the
/// glyph shape), narrower and degenerate for blank glyphs. We print the full loose box (what
/// layout grouping should use) and only the x-extent of the tight box, plus both gaps.
/// Mark params that carry replacement or alternate text (ISO 32000-1 §14.9).
const TEXT_PARAMS: [&str; 3] = ["ActualText", "Alt", "E"];

/// Marks as `Name(key=value …)`, outermost first, separated by ` > `.
fn fmt_marks(marks: &[tags::Mark]) -> String {
    marks
        .iter()
        .map(|m| {
            if m.params.is_empty() {
                return m.name.clone();
            }
            let ps: Vec<String> = m
                .params
                .iter()
                .map(|(k, v)| match v {
                    tags::MarkValue::Int(i) => format!("{k}={i}"),
                    tags::MarkValue::Str(s) => format!("{k}={:?}", truncate(s, 60)),
                    tags::MarkValue::Name(n) => format!("{k}=/{n}"),
                    tags::MarkValue::Other(t) => format!("{k}=<{t}>"),
                })
                .collect();
            format!("{}({})", m.name, ps.join(" "))
        })
        .collect::<Vec<_>>()
        .join(" > ")
}

/// Marks of the object at `path` (top-level index, then form children).
fn marks_at<'m>(marks: &'m [tags::ObjMarks], path: &[usize]) -> Option<&'m tags::ObjMarks> {
    let (first, rest) = path.split_first()?;
    let mut cur = marks.get(*first)?;
    for j in rest {
        cur = cur.children.get(*j)?;
    }
    Some(cur)
}

/// Char-level view of marks: for each char index, the object path and its marks.
type CharMarks<'a> = (Vec<Option<Vec<usize>>>, &'a Vec<tags::ObjMarks>);

fn dump_chars(page: &PdfPage, page_h: f32, region: Option<Region>, marks: Option<CharMarks>) {
    let text = match page.text() {
        Ok(t) => t,
        Err(e) => {
            outln!("-- chars: text layer unavailable ({e:?})");
            return;
        }
    };
    let chars = text.chars();
    let total = chars.len();
    match region {
        Some(r) => outln!(
            "-- chars ({total} on page; region x={} y={} w={} h={}, by loose-box center)",
            r.x,
            r.y,
            r.w,
            r.h
        ),
        None => outln!("-- chars ({total} on page)"),
    }
    if let Some((objs, _)) = &marks {
        // The char -> object map comes from a second text page on the raw handle; it lines
        // up with this one only if both have the same chars.
        if objs.len() != total {
            outln!(
                "     (warning: raw text page has {} chars, not {total}; obj= may be off)",
                objs.len()
            );
        }
        outln!(
            "     (--marks: obj= is the source object, '-' = none, e.g. generated; text params from its innermost marks)"
        );
    }
    outln!(
        "     idx  char      g  loose: x      y     w     h | tight x0-x1   | orig x  base y | size font                   | gapL  gapT  gapL/size"
    );
    let mut prev: Option<PrevChar> = None;
    let mut shown = 0usize;
    // Iterate by index: the crate's iterator stops at the first char it fails to read.
    for i in 0..total {
        let Ok(c) = chars.get(i) else {
            outln!("  {i:>6}  (unreadable)");
            continue;
        };
        let generated = c.is_generated().unwrap_or(false);
        let loose = c.loose_bounds().ok();
        let tight = c.tight_bounds().ok();
        let origin = c.origin().ok();
        let size = c.scaled_font_size().value;
        let baseline = origin.map(|(_, y)| y.value);

        // Gap to the previous visible char on the same baseline. Whitespace (generated or
        // real) is skipped as "previous", so the gap is the distance between glyphs whether
        // or not the producer emitted a space glyph there (LaTeX never does; Typst, LibreOffice
        // and Chrome do inside a cell). Computed before region filtering, so the first char
        // inside the region still gets its gap.
        let blank = c.unicode_char().is_none_or(char::is_whitespace);
        let mut gap = None;
        if !generated && !blank {
            if let (Some(l), Some(b)) = (loose, baseline) {
                if let Some(p) = &prev {
                    if (p.baseline - b).abs() <= SAME_BASELINE_TOL * size.max(1.0) {
                        let gl = l.left().value - p.loose_right;
                        let gt = tight.map(|t| t.left().value - p.tight_right);
                        gap = Some((gl, gt));
                    }
                }
                prev = Some(PrevChar {
                    baseline: b,
                    loose_right: l.right().value,
                    tight_right: tight.map_or(l.right().value, |t| t.right().value),
                });
            }
        }

        if let Some(r) = region {
            let inside = loose.is_some_and(|l| {
                let cx = (l.left().value + l.right().value) / 2.0;
                let cy = page_h - (l.top().value + l.bottom().value) / 2.0;
                r.contains(cx, cy)
            });
            if !inside {
                continue;
            }
        }
        shown += 1;

        let ch = match c.unicode_char() {
            Some(ch) => format!("{ch:?}"),
            None => format!("U+{:04X}", c.unicode_value()),
        };
        let loose_s = loose.map_or("?".into(), |l| {
            format!(
                "{:>6.2} {:>6.2} {:>5.2} {:>5.2}",
                l.left().value,
                page_h - l.top().value,
                l.width().value,
                l.height().value
            )
        });
        let tight_s = tight.map_or("?".into(), |t| {
            format!("{:>6.2}-{:>6.2}", t.left().value, t.right().value)
        });
        let origin_s = origin.map_or("?".into(), |(x, y)| {
            format!("{:>6.2} {:>7.2}", x.value, page_h - y.value)
        });
        let gap_s = match gap {
            Some((gl, gt)) => format!(
                "{gl:>5.2} {} {:>5.2}",
                gt.map_or("    ?".into(), |g| format!("{g:>5.2}")),
                if size > 0.0 { gl / size } else { 0.0 }
            ),
            None => String::new(),
        };
        let mut extra = Vec::new();
        if let Ok(a) = c.angle_degrees() {
            if a.abs() > 0.01 {
                extra.push(format!("angle={a:.1}"));
            }
        }
        if let Some((objs, obj_marks)) = &marks {
            match objs.get(i).and_then(|p| p.as_ref()) {
                Some(path) => {
                    let p: Vec<String> = path.iter().map(|n| n.to_string()).collect();
                    extra.push(format!("obj={}", p.join(".")));
                    // Innermost mark carrying each text param is the one that applies.
                    if let Some(m) = marks_at(obj_marks, path) {
                        for key in TEXT_PARAMS {
                            if let Some(v) = m.marks.iter().rev().find_map(|mk| mk.str_param(key)) {
                                extra.push(format!("{key}={:?}", truncate(v, 40)));
                            }
                        }
                    }
                }
                None => extra.push("obj=-".into()),
            }
        }
        if c.is_hyphen().unwrap_or(false) {
            extra.push("hyphen".into());
        }
        // pdfium-render 0.9.6 inverts FPDFText_HasUnicodeMapError (PDFium returns 1 when the
        // char HAS a map error; the crate maps 1 to `false`). Every char of every corpus PDF
        // came back `true`, so we negate here. Revisit when upgrading the crate (achado 002).
        if !c.has_unicode_map_error().unwrap_or(true) {
            extra.push("unicode-map-error".into());
        }
        outln!(
            "  {i:>6}  {ch:<8}  {}  {loose_s} | {tight_s} | {origin_s} | {size:>4.1} {:<22} | {gap_s}{}",
            if generated { "G" } else { "." },
            truncate(strip_subset(&c.font_name()), 22),
            if extra.is_empty() {
                String::new()
            } else {
                format!("  [{}]", extra.join(","))
            },
        );
    }
    if region.is_some() {
        outln!("     ({shown} chars in region)");
    }
}

/// Drops the `ABCDEF+` subset prefix, which only adds noise in the per-char listing.
fn strip_subset(name: &str) -> &str {
    match name.split_once('+') {
        Some((p, rest)) if p.len() == 6 && p.bytes().all(|b| b.is_ascii_uppercase()) => rest,
        _ => name,
    }
}

fn print_elem(e: &tags::Elem, depth: usize) {
    let mut line = format!("{}{}", "  ".repeat(depth), e.kind);
    // -1 entries are kids that are structure elements, not marked content.
    let ids: Vec<String> = e
        .mcids
        .iter()
        .filter(|m| **m >= 0)
        .map(|m| m.to_string())
        .collect();
    if !ids.is_empty() {
        line.push_str(&format!(" mcid={}", ids.join(",")));
    }
    if let Some(a) = &e.alt {
        line.push_str(&format!(" alt={:?}", truncate(a, 60)));
    }
    if let Some(a) = &e.actual_text {
        line.push_str(&format!(" actual={:?}", truncate(a, 60)));
    }
    if let Some(a) = &e.expansion {
        line.push_str(&format!(" e={:?}", truncate(a, 60)));
    }
    outln!("{line}");
    for c in &e.children {
        print_elem(c, depth + 1);
    }
}

fn fmt_rect(r: &PdfRect, page_h: f32) -> String {
    format!(
        "x={:>5.1} y={:>5.1} w={:>5.1} h={:>4.1}",
        r.left().value,
        page_h - r.top().value,
        r.width().value,
        r.height().value
    )
}

fn weight_value(w: PdfFontWeight) -> u32 {
    match w {
        PdfFontWeight::Weight100 => 100,
        PdfFontWeight::Weight200 => 200,
        PdfFontWeight::Weight300 => 300,
        PdfFontWeight::Weight400Normal => 400,
        PdfFontWeight::Weight500 => 500,
        PdfFontWeight::Weight600 => 600,
        PdfFontWeight::Weight700Bold => 700,
        PdfFontWeight::Weight800 => 800,
        PdfFontWeight::Weight900 => 900,
        PdfFontWeight::Custom(v) => v,
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut t: String = s.chars().take(max).collect();
        t.push('…');
        t
    }
}