kakemono 0.12.0

Convert scientific-paper PDFs (arXiv) and Word documents into clean, readable HTML in four fidelity modes, Word documents, Markdown, LaTeX or EPUB books
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Runs the PDF interpreter over a page and records everything the layout
//! analysis needs: positioned glyphs with their fonts, image placements and
//! the bounding boxes of vector drawing operations.

use super::fonts::{FontRegistry, UNKNOWN_FONT};
use super::symbols::MAPSTO_STEM;
use crate::common::geom::Rect;
use hayro_interpret::font::{Glyph as PdfGlyph, GlyphRun};
use hayro_interpret::hayro_cmap::BfString;
use hayro_interpret::util::TransformExt;
use hayro_interpret::{
    BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image, ImageDrawProps, InterpreterCache,
    InterpreterSettings, Paint, SoftMask, interpret_page,
};
use hayro_syntax::page::Page;
use kurbo::{Affine, BezPath, Point, Shape};

/// Height of a glyph's nominal box above the baseline, in multiples of the
/// font size (roughly the ascender height of Latin text fonts).
const EM_BOX_ASCENT_EM: f32 = 0.75;
/// Depth of a glyph's nominal box below the baseline, in multiples of the
/// font size (roughly the descender depth of Latin text fonts).
const EM_BOX_DESCENT_EM: f32 = 0.22;
/// A colour whose red, green and blue channels all exceed this value counts
/// as white (white boxes are often used to mask parts of a figure).
const WHITE_CHANNEL_MIN: u8 = 250;
/// Maximum thickness of a path that can be a rule, in points.
const RULE_MAX_THICKNESS_PT: f32 = 2.5;
/// Minimum length of a rule, in multiples of its thickness.
const RULE_MIN_ASPECT: f32 = 4.0;
/// Thickness assumed for the aspect test of rules thinner than this (in
/// points), so that hairlines of zero width still need some length.
const RULE_MIN_THICKNESS_PT: f32 = 0.5;
/// Colour recorded for pattern (gradient, tiling) paints, which have no
/// single colour: an opaque mid grey, so they are neither white nor
/// transparent.
const PATTERN_COLOR: [u8; 4] = [128, 128, 128, 255];
/// Clip rectangle standing for an empty clip: a tiny box far outside any
/// page, so that nothing drawn inside it is visible.
const EMPTY_CLIP: kurbo::Rect = kurbo::Rect::new(-1e6, -1e6, -1e6 + 1e-3, -1e6 + 1e-3);
/// Glyphs whose origin lies up to this far outside the clip rectangle are
/// still kept, in points (origins on the clip edge are common and harmless).
const GLYPH_CLIP_MARGIN_PT: f64 = 2.0;
/// Units per em of glyph space, the PDF convention for font metrics.
const GLYPH_UNITS_PER_EM: f64 = 1000.0;
/// Glyphs smaller than this (in points) are dropped: they are invisible
/// text or degenerate transforms.
const MIN_GLYPH_SIZE_PT: f32 = 0.5;
/// Glyphs whose baseline deviates less than this from horizontal (in
/// degrees) count as horizontal text.
const HORIZONTAL_MAX_ANGLE_DEG: f32 = 3.0;
/// Advance assumed for glyphs without a width, in glyph units (half an em).
const DEFAULT_ADVANCE_UNITS: f32 = 500.0;
/// Height of the ink box above the baseline assumed for glyphs without an
/// outline, in multiples of the font size.
const FALLBACK_INK_ASCENT_EM: f32 = 0.7;
/// Depth of the ink box below the baseline assumed for glyphs without an
/// outline, in multiples of the font size.
const FALLBACK_INK_DESCENT_EM: f32 = 0.2;
/// A glyph mapped to `=` whose outline is this many times taller than wide
/// is a slash: an equals sign is always wider than tall. Some publishers'
/// fonts (APS) keep the TeX math italic layout, where the code of `=` holds
/// the slash, but declare a text encoding.
const SLASH_MIN_ASPECT: f64 = 1.5;
/// Images whose visible part is not wider and taller than this (in points)
/// are ignored (invisible placeholder images, masks of single pixels).
const MIN_IMAGE_SIDE_PT: f32 = 0.5;
/// A stencil mask with at most this many pixels, stretched over a long thin
/// box, is a rule: some producers draw table lines as one-pixel masks.
const STENCIL_RULE_MAX_PIXELS: u32 = 1;
/// Number of path elements recorded for a rule drawn as a stencil mask (the
/// four sides of a rectangle and its closing).
const STENCIL_RULE_ELEMENTS: u16 = 5;

/// A picture of a single pixel stretched into a thin bar is a rule drawn
/// the way some typesetters draw table rules (ATLAS): it is recorded in
/// [`RawPage::pixel_rules`] as a filled path. This is the colour assumed for
/// it (black: the pixel is not read).
const PIXEL_RULE_COLOR: [u8; 4] = [0, 0, 0, 255];
/// A single-pixel picture is a rule when its thin side is at most this
/// (in points).
const PIXEL_RULE_MAX_THICKNESS_PT: f32 = 2.0;
/// The arrow of ↦ starts within this distance of its stem (in em), on the
/// same baseline.
const MAPSTO_MAX_OFFSET_EM: f32 = 0.3;

/// Text direction of a glyph, quantised to quarter turns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dir {
    /// Regular left-to-right text.
    Horizontal,
    /// Any rotated text (axis labels, the arXiv margin stamp, ...).
    Rotated,
}

/// A glyph as drawn on the page, in page coordinates (points, y down).
#[derive(Debug, Clone)]
pub struct Glyph {
    /// The text the glyph stands for, normalised (ligatures expanded,
    /// special spaces and hyphens replaced, control characters removed).
    /// U+FFFD when the PDF gives no Unicode mapping.
    pub text: String,
    /// Origin on the baseline.
    pub x: f32,
    /// Vertical coordinate of the origin (see [`Glyph::x`]).
    pub y: f32,
    /// Advance along the baseline.
    pub adv: f32,
    /// Font size in points (the vertical scale of the glyph transform).
    pub size: f32,
    /// Index into the document's font table ([`UNKNOWN_FONT`] for Type 3
    /// glyphs and glyphs whose font could not be identified).
    pub font: u16,
    /// Direction of the baseline.
    pub dir: Dir,
    /// Rotation in degrees (0 for horizontal text).
    pub angle: f32,
    /// Drawn in the invisible text rendering mode (OCR layers of scans).
    pub invisible: bool,
    /// Fill colour as RGB.
    pub color: [u8; 3],
    /// Bounding box of the glyph's actual outline.
    pub ink: Rect,
}

impl Glyph {
    /// Nominal box of the glyph (em box, not the ink).
    ///
    /// For rotated glyphs this is a square around the origin that contains
    /// the glyph whatever its direction.
    pub fn bbox(&self) -> Rect {
        match self.dir {
            Dir::Horizontal => Rect::new(
                self.x,
                self.y - EM_BOX_ASCENT_EM * self.size,
                self.x + self.adv.max(0.0),
                self.y + EM_BOX_DESCENT_EM * self.size,
            ),
            Dir::Rotated => {
                let radius = self.size.max(self.adv.abs());
                Rect::new(self.x - radius, self.y - radius, self.x + radius, self.y + radius)
            }
        }
    }
}

/// Where a raster image is placed on the page.
#[derive(Debug, Clone, Copy)]
pub struct ImageBox {
    /// Visible part of the image on the page.
    pub bbox: Rect,
    /// Width of the image in pixels.
    pub px_width: u32,
    /// Height of the image in pixels.
    pub px_height: u32,
}

/// A filled or stroked vector path, reduced to its bounding box.
#[derive(Debug, Clone, Copy)]
pub struct PathBox {
    /// Visible part of the path's bounding box (including half the stroke
    /// width for stroked paths).
    pub bbox: Rect,
    /// The path is stroked.
    pub stroked: bool,
    /// The path is filled.
    pub filled: bool,
    /// Paint colour as RGBA.
    pub color: [u8; 4],
    /// Stroke width on the page in points (0 for fills).
    pub line_width: f32,
    /// Number of path elements; 5 or fewer usually means a line or a box.
    pub elements: u16,
}

impl PathBox {
    /// The path is painted white (or nearly so), e.g. a mask over part of a
    /// figure.
    pub fn is_white(&self) -> bool {
        self.color[0] > WHITE_CHANNEL_MIN && self.color[1] > WHITE_CHANNEL_MIN && self.color[2] > WHITE_CHANNEL_MIN
    }

    /// A thin horizontal line (table rule, footnote rule, fraction bar).
    pub fn is_hrule(&self) -> bool {
        self.bbox.height() <= RULE_MAX_THICKNESS_PT
            && self.bbox.width() >= RULE_MIN_ASPECT * self.bbox.height().max(RULE_MIN_THICKNESS_PT)
    }

    /// A thin vertical line (table rule, column separator).
    pub fn is_vrule(&self) -> bool {
        self.bbox.width() <= RULE_MAX_THICKNESS_PT
            && self.bbox.height() >= RULE_MIN_ASPECT * self.bbox.width().max(RULE_MIN_THICKNESS_PT)
    }
}

/// Everything recorded on one page.
#[derive(Debug, Default)]
pub struct RawPage {
    /// Zero-based page index.
    pub index: usize,
    /// Page width in points (after the page's rotation).
    pub width: f32,
    /// Page height in points (after the page's rotation).
    pub height: f32,
    /// Glyphs in drawing order.
    pub glyphs: Vec<Glyph>,
    /// Raster images in drawing order.
    pub images: Vec<ImageBox>,
    /// Vector paths in drawing order.
    pub paths: Vec<PathBox>,
    /// Bars drawn as a stretched picture of one pixel (see
    /// [`PIXEL_RULE_MAX_THICKNESS_PT`]). They are kept apart from `paths`:
    /// only table rules are read from them, the detection of figures and
    /// captions does not see them.
    pub pixel_rules: Vec<PathBox>,
    /// Areas of the page that link to a web address.
    pub links: Vec<LinkArea>,
}

/// An area of a page that opens a URL (a link annotation).
#[derive(Debug, Clone)]
pub struct LinkArea {
    /// The area, in page coordinates.
    pub rect: Rect,
    /// The URL.
    pub uri: std::sync::Arc<str>,
}

/// URL schemes kept from link annotations; others (`javascript:`, local
/// files) are dropped.
const LINK_SCHEMES: &[&str] = &["http://", "https://", "mailto:", "ftp://"];

/// The link annotations of `page` that open a URL, in page coordinates.
fn uri_links(page: &Page<'_>) -> Vec<LinkArea> {
    use hayro_syntax::object::{Array, Dict, Name, Rect as PdfRect, String as PdfString};
    let transform = page.initial_transform(true).to_kurbo();
    let Some(annots) = page.raw().get::<Array>(b"Annots") else {
        return Vec::new();
    };
    annots
        .iter::<Dict>()
        .filter_map(|annot| {
            if annot.get::<Name>(b"Subtype")?.as_ref() != b"Link" {
                return None;
            }
            let action = annot.get::<Dict>(b"A")?;
            if action.get::<Name>(b"S")?.as_ref() != b"URI" {
                return None;
            }
            let uri = action.get::<PdfString>(b"URI")?;
            let uri = std::str::from_utf8(uri.as_bytes()).ok()?.trim();
            let lower = uri.to_ascii_lowercase();
            if !LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
                return None;
            }
            let area = annot.get::<PdfRect>(b"Rect")?;
            let area = transform.transform_rect_bbox(kurbo::Rect::new(area.x0, area.y0, area.x1, area.y1));
            Some(LinkArea {
                rect: Rect::new(area.x0 as f32, area.y0 as f32, area.x1 as f32, area.y1 as f32),
                uri: std::sync::Arc::from(uri),
            })
        })
        .collect()
}

/// The interpreter's output device: receives drawing operations and
/// records them into a [`RawPage`].
struct Extractor<'r, 'a> {
    /// Fonts of the document, used to identify the font of each glyph.
    fonts: &'r mut FontRegistry<'a>,
    /// The page being recorded.
    page: RawPage,
    /// The whole page, the clip when no clip path is active.
    page_rect: kurbo::Rect,
    /// Stack of active clip rectangles (bounding boxes of the clip paths,
    /// each intersected with the one below).
    clips: Vec<kurbo::Rect>,
}

/// Position, size and direction of a glyph on the page, from its transform.
struct GlyphPlacement {
    /// Glyph origin on the page.
    origin: Point,
    /// Font size in points (vertical scale of the transform).
    size: f32,
    /// Horizontal scale of the transform, in points per em.
    x_scale: f64,
    /// Rotation of the baseline in degrees.
    angle: f32,
    /// Direction of the baseline.
    dir: Dir,
}

impl GlyphPlacement {
    /// Reads the placement of a glyph from its transform (glyph space to
    /// page). Returns `None` for glyphs whose origin lies outside `clip`
    /// (with a small margin) and for glyphs too small to be real text.
    fn new(transform: Affine, clip: kurbo::Rect) -> Option<Self> {
        let origin = transform * Point::ZERO;
        if origin.x < clip.x0 - GLYPH_CLIP_MARGIN_PT
            || origin.x > clip.x1 + GLYPH_CLIP_MARGIN_PT
            || origin.y < clip.y0 - GLYPH_CLIP_MARGIN_PT
            || origin.y > clip.y1 + GLYPH_CLIP_MARGIN_PT
        {
            return None;
        }
        let [xx, yx, xy, yy, _, _] = transform.as_coeffs();
        let size = (xy.hypot(yy) * GLYPH_UNITS_PER_EM) as f32;
        let x_scale = xx.hypot(yx) * GLYPH_UNITS_PER_EM;
        if size < MIN_GLYPH_SIZE_PT || !size.is_finite() {
            return None;
        }
        let angle = (yx.atan2(xx)).to_degrees() as f32;
        let dir = if angle.abs() < HORIZONTAL_MAX_ANGLE_DEG {
            Dir::Horizontal
        } else {
            Dir::Rotated
        };
        Some(Self {
            origin,
            size,
            x_scale,
            angle,
            dir,
        })
    }
}

impl Extractor<'_, '_> {
    /// Joins an arrow at `placement` to the stem of ↦ drawn just before it
    /// ([`MAPSTO_STEM`]): the stem glyph takes the arrow's extent. Returns
    /// whether the arrow was joined.
    fn join_mapsto(&mut self, placement: &GlyphPlacement, adv: f32, ink: Rect) -> bool {
        let Some(stem) = self.page.glyphs.last_mut() else {
            return false;
        };
        let (x, y) = (placement.origin.x as f32, placement.origin.y as f32);
        let near = (stem.y - y).abs() <= MAPSTO_MAX_OFFSET_EM * placement.size
            && (x - stem.x).abs() <= MAPSTO_MAX_OFFSET_EM * placement.size;
        if stem.text != MAPSTO_STEM || !near {
            return false;
        }
        stem.adv = (x + adv - stem.x).max(stem.adv);
        stem.ink = stem.ink.union(&ink);
        true
    }

    /// The active clip rectangle.
    fn clip(&self) -> kurbo::Rect {
        self.clips.last().copied().unwrap_or(self.page_rect)
    }

    /// The part of `bbox` inside the active clip, or `None` when they do
    /// not touch. Boxes of zero area (straight lines) are kept when they
    /// touch the clip.
    fn visible(&self, bbox: kurbo::Rect) -> Option<Rect> {
        let clip = self.clip();
        let inside = bbox.intersect(clip);
        // `intersect` of disjoint rects yields a zero-area rect, lines also
        // have zero area, so test for overlap explicitly.
        if bbox.x0 > clip.x1 || bbox.x1 < clip.x0 || bbox.y0 > clip.y1 || bbox.y1 < clip.y0 {
            return None;
        }
        Some(Rect::new(
            inside.x0 as f32,
            inside.y0 as f32,
            inside.x1 as f32,
            inside.y1 as f32,
        ))
    }

    /// Records a one-pixel stencil mask as a filled path of the box it is
    /// stretched over, in the colour it is painted with. Masks that do not
    /// paint their pixel (or are not visible) leave nothing.
    fn record_stencil_rule(&mut self, stencil: &hayro_interpret::StencilImage<'_, '_>, bbox: kurbo::Rect) {
        let mut painted = false;
        let mut color = [0, 0, 0, 255];
        stencil.with_stencil(
            |luma, paint| {
                painted = luma.data.first().is_some_and(|&sample| sample != 0);
                color = paint_color(paint);
            },
            None,
        );
        if !painted || color[3] == 0 {
            return;
        }
        let Some(bbox) = self.visible(bbox) else {
            return;
        };
        self.page.paths.push(PathBox {
            bbox,
            stroked: false,
            filled: true,
            color,
            line_width: 0.0,
            elements: STENCIL_RULE_ELEMENTS,
        });
    }

    /// Text, advance (in glyph units), font index and outline box (in glyph
    /// space) of a glyph. Outline glyphs are identified through the font
    /// registry; Type 3 glyphs have no outline and an unknown font.
    fn describe_glyph(&mut self, glyph: &PdfGlyph<'_>) -> (Option<BfString>, Option<f32>, u16, Option<kurbo::Rect>) {
        match glyph {
            PdfGlyph::Outline(outline) => (
                outline.as_unicode(),
                outline.advance_width(),
                self.fonts.identify(outline),
                self.fonts.outline_bbox(outline),
            ),
            PdfGlyph::Type3(type3) => (type3.as_unicode(), type3.advance_width(), UNKNOWN_FONT, None),
        }
    }
}

impl<'a> Device<'a> for Extractor<'_, 'a> {
    fn draw_path(&mut self, path: &BezPath, props: DrawProps<'a>, draw_mode: &DrawMode) {
        let (stroked, filled, line_width) = match draw_mode {
            DrawMode::Fill(_) => (false, true, 0.0),
            DrawMode::Stroke(stroke) => (true, false, stroke.line_width),
            DrawMode::FillAndStroke(_, stroke) => (true, true, stroke.line_width),
            DrawMode::Invisible => return,
        };
        let color = paint_color(&props.paint);
        if color[3] == 0 {
            return;
        }
        let [xx, yx, xy, yy, _, _] = props.transform.as_coeffs();
        let scale = ((xx * yy - yx * xy).abs()).sqrt();
        let line_width_page = line_width as f64 * scale;
        let mut bbox = props.transform.transform_rect_bbox(path.bounding_box());
        if stroked {
            bbox = bbox.inflate(line_width_page * 0.5, line_width_page * 0.5);
        }
        let Some(bbox) = self.visible(bbox) else {
            return;
        };
        self.page.paths.push(PathBox {
            bbox,
            stroked,
            filled,
            color,
            line_width: line_width_page as f32,
            elements: path.elements().len().min(u16::MAX as usize) as u16,
        });
    }

    fn push_clip_path(&mut self, clip_path: &ClipPath) {
        let bbox = clip_path.path.bounding_box();
        let current = self.clip();
        let mut clip = bbox.intersect(current);
        if bbox.x0 > current.x1 || bbox.x1 < current.x0 || bbox.y0 > current.y1 || bbox.y1 < current.y0 {
            // Empty clip: nothing drawn inside is visible.
            clip = EMPTY_CLIP;
        }
        self.clips.push(clip);
    }

    fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}

    fn draw_glyph_run(&mut self, glyph_run: &GlyphRun<'_, 'a>, props: DrawProps<'a>, draw_mode: &DrawMode) {
        let invisible = matches!(draw_mode, DrawMode::Invisible);
        let color = paint_color(&props.paint);
        let clip = self.clip();
        for glyph in glyph_run.glyphs() {
            let transform: Affine = props.transform * glyph.transform();
            let Some(placement) = GlyphPlacement::new(transform, clip) else {
                continue;
            };
            let (unicode, advance, font, outline_box) = self.describe_glyph(glyph);
            let info = &self.fonts.infos[font as usize];
            let private = match (&unicode, info.symbols) {
                (Some(BfString::Char(ch)), Some(symbols)) => symbols.private_text(*ch),
                _ => None,
            };
            let mut text = match (info.mathabx, private) {
                (Some(abx), _) => abx.text(glyph.char_code()).unwrap_or("\u{FFFD}").to_string(),
                (None, Some(known)) => known.to_string(),
                (None, None) => glyph_text(unicode, info.libertine),
            };
            // A symbol font of known encoding fills in what the PDF leaves unmapped.
            if text == "\u{FFFD}"
                && let Some(known) = info.symbols.and_then(|symbols| symbols.text(glyph.char_code()))
            {
                text = known;
            }
            // Control codes (a line break typed into a figure label) draw
            // nothing; neither does an unmapped glyph without an outline (a
            // space of a font without Unicode mapping, padding a form).
            let blank = font != UNKNOWN_FONT && outline_box.is_none();
            if text.is_empty() || text == "\u{FFFD}" && (matches!(glyph.char_code(), 9 | 10 | 13) || blank) {
                continue;
            }
            if self.fonts.infos[font as usize].math_pi {
                text = remap_math_pi(&text);
            }
            if self.fonts.infos[font as usize].math {
                text = remap_tex_math(&text);
            }
            if self.fonts.infos[font as usize].radical_pi {
                // The radical sign and the pieces of its bar, encoded on
                // letters: the bar is drawn, not read.
                text = match text.as_str() {
                    "p" => "√".into(),
                    "ffi" | "ff" | "fi" | "fl" => continue,
                    _ => text,
                };
            }
            if text == "=" && outline_box.is_some_and(|outline| outline.height() > SLASH_MIN_ASPECT * outline.width()) {
                text = "/".into();
            }
            // Use the horizontal extent of the transform so that horizontally
            // scaled text keeps correct advances.
            let adv = advance.unwrap_or(DEFAULT_ADVANCE_UNITS) as f64 / GLYPH_UNITS_PER_EM * placement.x_scale;
            let ink = ink_box(outline_box, transform, &placement, adv);
            if text == "\u{2192}" && self.join_mapsto(&placement, adv as f32, ink) {
                continue;
            }
            self.page.glyphs.push(Glyph {
                text,
                x: placement.origin.x as f32,
                y: placement.origin.y as f32,
                adv: adv as f32,
                size: placement.size,
                font,
                dir: placement.dir,
                angle: placement.angle,
                invisible,
                color: [color[0], color[1], color[2]],
                ink,
            });
        }
    }

    fn draw_image(&mut self, image: Image<'a, '_>, props: ImageDrawProps<'a>) {
        let (px_width, px_height) = (image.width(), image.height());
        let rect = kurbo::Rect::new(0.0, 0.0, px_width as f64, px_height as f64);
        let bbox = props.transform.transform_rect_bbox(rect);
        // A tiny stencil mask stretched thin is a rule (table rules in some
        // typesetting): it takes part in float and table detection.
        let mut rule = false;
        if px_width * px_height <= STENCIL_RULE_MAX_PIXELS
            && let Image::Stencil(stencil) = &image
        {
            self.record_stencil_rule(stencil, bbox);
            rule = true;
        }
        // A 1x1 image stretched into a bar is drawn as a rectangle in the
        // hard-95 page picture and gives table rules (see `pixel_rules`).
        if (px_width, px_height) == (1, 1)
            && let Some(bar) = self.visible(bbox)
            && bar.width().min(bar.height()) <= PIXEL_RULE_MAX_THICKNESS_PT
            && bar.width().max(bar.height()) > MIN_IMAGE_SIDE_PT
        {
            self.page.pixel_rules.push(PathBox {
                bbox: bar,
                stroked: false,
                filled: true,
                color: PIXEL_RULE_COLOR,
                line_width: 0.0,
                elements: 5,
            });
            rule = true;
        }
        if rule {
            return;
        }
        if let Some(bbox) = self.visible(bbox)
            && bbox.width() > MIN_IMAGE_SIDE_PT
            && bbox.height() > MIN_IMAGE_SIDE_PT
        {
            self.page.images.push(ImageBox {
                bbox,
                px_width,
                px_height,
            });
        }
    }

    fn pop_clip(&mut self) {
        self.clips.pop();
    }

    fn pop_transparency_group(&mut self) {}
}

/// Interprets one page and returns its raw content.
///
/// `index` is the zero-based page number recorded in the result. `fonts`
/// is switched to the fonts of this page (see
/// [`FontRegistry::begin_page`]) and learns any new fonts; `cache` and
/// `settings` are the interpreter's, reused across the pages of one thread.
pub fn extract_page<'a>(
    page: &'a Page<'a>,
    index: usize,
    fonts: &mut FontRegistry<'a>,
    cache: &InterpreterCache<'a>,
    settings: &InterpreterSettings,
) -> RawPage {
    let (width, height) = page.render_dimensions();
    let page_rect = kurbo::Rect::new(0.0, 0.0, width as f64, height as f64);
    let mut ctx = Context::new(
        page.initial_transform(true).to_kurbo(),
        page_rect,
        cache,
        page.xref(),
        settings.clone(),
    );
    fonts.begin_page(page);
    let mut device = Extractor {
        fonts,
        page: RawPage {
            index,
            width,
            height,
            ..Default::default()
        },
        page_rect,
        clips: Vec::new(),
    };
    interpret_page(page, &mut ctx, &mut device);
    device.page.links = uri_links(page);
    device.page
}

/// RGBA colour of a paint; pattern paints get [`PATTERN_COLOR`].
fn paint_color(paint: &Paint<'_>) -> [u8; 4] {
    match paint {
        Paint::Color(color) => color.to_rgba().to_rgba8(),
        Paint::Pattern(_) => PATTERN_COLOR,
    }
}

/// The normalised text of a glyph's Unicode mapping: U+FFFD when there is
/// none, and empty when the mapping holds only characters that are dropped
/// (control characters, zero-width spaces). The private-use code points of
/// Linux Libertine are read first when `libertine` is set.
fn glyph_text(unicode: Option<BfString>, libertine: bool) -> String {
    let mut text = String::new();
    let raw = match unicode {
        Some(BfString::Char(ch)) => ch.to_string(),
        Some(BfString::String(string)) => string,
        None => return '\u{FFFD}'.to_string(),
    };
    if libertine {
        normalize_text(&libertine_text(&raw), &mut text);
    } else {
        normalize_text(&raw, &mut text);
    }
    text
}

/// Reads the private-use code points that Linux Libertine and Biolinum give
/// their ligatures ("Th", "tt", "ft", ...), small capitals (as lowercase
/// letters) and old-style figures. Other characters are kept.
fn libertine_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        let code = ch as u32;
        match code {
            0xE039 => out.push_str("ft"),
            0xE03A => out.push_str("ck"),
            0xE03B => out.push_str("ch"),
            0xE03C => out.push_str("tt"),
            0xE048 => out.push_str("Qu"),
            0xE049 => out.push_str("Th"),
            0xE0E0 => out.push('f'),
            0xE051..=0xE06A => out.push(char::from(b'a' + (code - 0xE051) as u8)),
            0xE118..=0xE121 => out.push(char::from(b'0' + (code - 0xE118) as u8)),
            _ => out.push(ch),
        }
    }
    out
}

/// Appends `text` to `out`, expanding Latin ligatures, turning special
/// spaces into plain spaces and soft or non-breaking hyphens into `-`, and
/// dropping control characters, zero-width characters and the byte-order
/// mark, so that text from different PDF producers compares equal.
/// Private-use characters (a ligature such as "ft" that the font maps to a
/// code of its own) become U+FFFD: no other font draws them, so the glyph
/// must stay in the page picture.
fn normalize_text(text: &str, out: &mut String) {
    for ch in text.chars() {
        match ch {
            '\u{FB00}' => out.push_str("ff"),
            '\u{FB01}' => out.push_str("fi"),
            '\u{FB02}' => out.push_str("fl"),
            '\u{FB03}' => out.push_str("ffi"),
            '\u{FB04}' => out.push_str("ffl"),
            '\u{FB05}' | '\u{FB06}' => out.push_str("st"),
            '\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2009}' | '\u{200A}' | '\u{202F}' => out.push(' '),
            '\u{00AD}' => out.push('-'),
            '\u{2010}' | '\u{2011}' => out.push('-'),
            '\u{0}'..='\u{1F}' | '\u{7F}' | '\u{200B}'..='\u{200F}' | '\u{FEFF}' => {}
            '\u{F8E5}'..='\u{F8FE}' => out.push(symbol_piece(ch)),
            // Adobe's code points for old-style figures and small capitals
            // (Garamond Expert and other expert sets).
            '\u{F730}'..='\u{F739}' => out.push(char::from(b'0' + (ch as u32 - 0xF730) as u8)),
            '\u{F761}'..='\u{F77A}' => out.push(char::from(b'a' + (ch as u32 - 0xF761) as u8)),
            '\u{E000}'..='\u{F8FF}' => out.push('\u{FFFD}'),
            other => out.push(other),
        }
    }
}

/// The Unicode piece of a large delimiter or integral that the Adobe Symbol
/// encoding puts in the private-use area (U+F8E5 to U+F8FE), as TeX's cmex
/// and other math extension fonts are mapped in PDFs.
fn symbol_piece(ch: char) -> char {
    const PIECES: [char; 26] = [
        '\u{F8E5}', '\u{F8E6}', '\u{23AF}', '\u{AE}', '\u{A9}', '\u{2122}', '\u{239B}', '\u{239C}', '\u{239D}',
        '\u{23A1}', '\u{23A2}', '\u{23A3}', '\u{23A7}', '\u{23A8}', '\u{23A9}', '\u{23AA}', '\u{23AE}', '\u{239E}',
        '\u{239F}', '\u{23A0}', '\u{23A4}', '\u{23A5}', '\u{23A6}', '\u{23AB}', '\u{23AC}', '\u{23AD}',
    ];
    let piece = PIECES[(ch as u32 - 0xF8E5) as usize];
    if ('\u{E000}'..='\u{F8FF}').contains(&piece) {
        '\u{FFFD}'
    } else {
        piece
    }
}

/// Repairs the Unicode values that common TeX math fonts are given in
/// PDFs: the lunate epsilon of cmmi comes out as "ǫ" (o with ogonek) and the
/// box of msam as "✷" (an eight-spoked asterisk).
fn remap_tex_math(text: &str) -> String {
    text.chars()
        .map(|ch| match ch {
            '\u{01EB}' => '\u{03F5}',
            '\u{2737}' => '\u{25A1}',
            other => other,
        })
        .collect()
}

/// Undoes the encoding of "Mathematical Pi" fonts, which put math symbols
/// on Latin-1 letters: maps the letters back to the symbols they draw.
fn remap_math_pi(text: &str) -> String {
    text.chars()
        .map(|ch| match ch {
            '¼' => '=',
            'þ' => '+',
            'ð' => '(',
            'Þ' => ')',
            '½' => '[',
            'f' => '{',
            'g' => '}',
            other => other,
        })
        .collect()
}

/// Ink box of a glyph on the page: its outline box mapped through the
/// glyph's transform, or, for glyphs without an outline, a box of typical
/// proportions from the origin over the advance `adv`.
fn ink_box(outline_box: Option<kurbo::Rect>, transform: Affine, placement: &GlyphPlacement, adv: f64) -> Rect {
    let origin = placement.origin;
    let size = placement.size;
    match outline_box {
        Some(outline) => {
            let page_box = transform.transform_rect_bbox(outline);
            Rect::new(
                page_box.x0 as f32,
                page_box.y0 as f32,
                page_box.x1 as f32,
                page_box.y1 as f32,
            )
        }
        None => Rect::new(
            origin.x as f32,
            origin.y as f32 - FALLBACK_INK_ASCENT_EM * size,
            (origin.x + adv) as f32,
            origin.y as f32 + FALLBACK_INK_DESCENT_EM * size,
        ),
    }
}

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

    #[test]
    fn private_use_ligature_is_unknown() {
        // Linux Libertine maps its "ft" ligature to U+E039.
        let mut text = String::new();
        normalize_text("le\u{E039}most", &mut text);
        assert_eq!(text, "le\u{FFFD}most");
    }

    #[test]
    fn libertine_private_use_glyphs_are_read() {
        use super::libertine_text;
        assert_eq!(
            libertine_text("\u{E049}e pa\u{E03C}ern a\u{E039}er"),
            "The pattern after"
        );
        assert_eq!(
            libertine_text("\u{E05D}\u{E059}\u{E064} \u{E119}\u{E121}\u{E11F}\u{E120}"),
            "mit 1978"
        );
    }

    #[test]
    fn delimiter_pieces_are_read() {
        let mut text = String::new();
        normalize_text("\u{F8EB}\u{F8F4}\u{F8FE}", &mut text);
        assert_eq!(text, "\u{239B}\u{23AA}\u{23AD}");
    }
}