pdfpurr 0.4.0

A comprehensive pure-Rust PDF library for reading, writing, rendering, and validating PDF documents
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
//! OCR support for image-only PDF accessibility.
//!
//! Provides optical character recognition to make scanned/image-only PDFs
//! searchable and accessible. OCR text is overlaid as an invisible text
//! layer (rendering mode 3) on top of the original page image.
//!
//! # Architecture
//!
//! The OCR pipeline:
//! 1. Render the page to a pixel image
//! 2. Convert to grayscale
//! 3. Run OCR engine to get words + bounding boxes
//! 4. Generate invisible text layer with correct positioning
//! 5. Append the text layer to the page
//!
//! The [`OcrEngine`] trait abstracts over OCR backends:
//! - [`windows_engine::WindowsOcrEngine`] — Windows OCR (always available, ~95% accuracy)
//! - [`tesseract_engine::TesseractEngine`] — Tesseract CLI (always available, ~85-89%)
//! - `ocrs_engine::OcrsEngine` — pure-Rust ocrs (requires `ocr` feature, Latin only)

pub mod config;
pub mod constants;
pub mod engine;
pub mod hybrid;
pub mod layout;
#[cfg(feature = "ocr")]
pub mod ocrs_engine;
pub mod preprocess;
pub mod tesseract_engine;
pub mod text_layer;
pub mod windows_engine;
#[cfg(feature = "ocr-windows-native")]
pub mod windows_native_engine;

pub use config::OcrConfig;
pub use engine::{OcrEngine, OcrImage, OcrResult, OcrWord};
pub use text_layer::OCR_FONT_NAME;

/// Converts a `tiny_skia::Pixmap` (RGBA) to a grayscale [`OcrImage`].
///
/// Uses sRGB luminance coefficients (ITU-R BT.709):
/// `gray = 0.2126*R + 0.7152*G + 0.0722*B`
pub fn pixmap_to_grayscale(pixmap: &tiny_skia::Pixmap) -> OcrImage {
    let w = pixmap.width();
    let h = pixmap.height();
    let pixels = pixmap.pixels();
    let mut gray = Vec::with_capacity((w * h) as usize);

    for px in pixels {
        let r = px.red() as f32;
        let g = px.green() as f32;
        let b = px.blue() as f32;
        let a = px.alpha() as f32;

        // Unpremultiply alpha, then compute luminance
        if a > 0.0 {
            let r = r / a * 255.0;
            let g = g / a * 255.0;
            let b = b / a * 255.0;
            let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            gray.push(lum.round().clamp(0.0, 255.0) as u8);
        } else {
            gray.push(255); // transparent → white
        }
    }

    OcrImage {
        data: gray,
        width: w,
        height: h,
    }
}

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

    #[test]
    fn pixmap_to_grayscale_white() {
        let mut pixmap = tiny_skia::Pixmap::new(2, 2).unwrap();
        pixmap.fill(tiny_skia::Color::WHITE);
        let img = pixmap_to_grayscale(&pixmap);
        assert_eq!(img.width, 2);
        assert_eq!(img.height, 2);
        assert_eq!(img.data.len(), 4);
        // White pixels should produce ~255 grayscale
        assert!(img.data.iter().all(|&v| v >= 250));
    }

    #[test]
    fn pixmap_to_grayscale_black() {
        let mut pixmap = tiny_skia::Pixmap::new(2, 2).unwrap();
        pixmap.fill(tiny_skia::Color::BLACK);
        let img = pixmap_to_grayscale(&pixmap);
        // Black pixels should produce ~0 grayscale
        assert!(img.data.iter().all(|&v| v <= 5));
    }

    #[test]
    fn pixmap_to_grayscale_dimensions() {
        let pixmap = tiny_skia::Pixmap::new(100, 50).unwrap();
        let img = pixmap_to_grayscale(&pixmap);
        assert_eq!(img.width, 100);
        assert_eq!(img.height, 50);
        assert_eq!(img.data.len(), 5000);
    }

    use crate::core::objects::DictExt;

    /// Mock OCR engine for testing — returns fixed words.
    struct MockOcrEngine {
        words: Vec<OcrWord>,
    }

    impl OcrEngine for MockOcrEngine {
        fn recognize(&self, image: &OcrImage) -> crate::error::PdfResult<OcrResult> {
            Ok(OcrResult {
                words: self.words.clone(),
                image_width: image.width,
                image_height: image.height,
            })
        }
    }

    #[test]
    fn ocr_page_with_mock_engine() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "Hello".to_string(),
                x: 100,
                y: 100,
                width: 200,
                height: 40,
                confidence: 0.95,
            }],
        };
        let config = OcrConfig::default();

        let applied = doc.ocr_page(0, &engine, &config).unwrap();
        assert!(applied, "OCR should be applied to blank page");

        // Verify the page now has content
        let page = doc.get_page(0).unwrap();
        assert!(page.get_str("Contents").is_some());
    }

    #[test]
    fn ocr_page_skips_text_pages() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        // Add some text content to the page first
        let content = b"BT /F1 12 Tf 100 700 Td (Existing text) Tj ET";
        let helv = crate::fonts::standard14::Standard14Font::from_name("Helvetica").unwrap();
        let mut fonts = crate::core::objects::Dictionary::new();
        fonts.insert(
            crate::core::objects::PdfName::new("F1"),
            crate::core::objects::Object::Dictionary(helv.to_font_dictionary()),
        );
        doc.append_content_stream(0, content, Some(fonts)).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "OCR".to_string(),
                x: 0,
                y: 0,
                width: 100,
                height: 30,
                confidence: 0.9,
            }],
        };
        let config = OcrConfig {
            skip_text_pages: true,
            ..Default::default()
        };

        let applied = doc.ocr_page(0, &engine, &config).unwrap();
        assert!(!applied, "Should skip page that already has text");
    }

    #[test]
    fn ocr_text_extractable_after_apply() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        let engine = MockOcrEngine {
            words: vec![
                OcrWord {
                    text: "Hello".to_string(),
                    x: 100,
                    y: 100,
                    width: 200,
                    height: 40,
                    confidence: 0.95,
                },
                OcrWord {
                    text: "World".to_string(),
                    x: 350,
                    y: 100,
                    width: 200,
                    height: 40,
                    confidence: 0.92,
                },
            ],
        };

        let applied = doc.ocr_page(0, &engine, &OcrConfig::default()).unwrap();
        assert!(applied);

        // The invisible OCR text should be extractable
        let text = doc.extract_page_text(0).unwrap_or_default();
        assert!(
            text.contains("Hello"),
            "Extracted text should contain 'Hello', got: {:?}",
            text
        );
        assert!(
            text.contains("World"),
            "Extracted text should contain 'World', got: {:?}",
            text
        );
    }

    #[test]
    fn ocr_text_survives_roundtrip() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "Roundtrip".to_string(),
                x: 100,
                y: 100,
                width: 300,
                height: 40,
                confidence: 0.95,
            }],
        };

        doc.ocr_page(0, &engine, &OcrConfig::default()).unwrap();

        // Save to bytes and reload
        let bytes = doc.to_bytes().unwrap();
        let reloaded = Document::from_bytes(&bytes).unwrap();
        let text = reloaded.extract_page_text(0).unwrap_or_default();
        assert!(
            text.contains("Roundtrip"),
            "OCR text should survive save/reload, got: {:?}",
            text
        );
    }

    #[test]
    fn ocr_text_extractable_on_page_with_existing_image_content() {
        // Simulates a scanned PDF: page has existing content (image Do),
        // then OCR appends invisible text. Text extraction must find the OCR text.
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        // Add fake image content (simulates scanned page)
        let image_content = b"q 612 0 0 792 0 0 cm /Im0 Do Q";
        doc.append_content_stream(0, image_content, None).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "ScannedText".to_string(),
                x: 100,
                y: 100,
                width: 300,
                height: 40,
                confidence: 0.95,
            }],
        };

        doc.ocr_page(0, &engine, &OcrConfig::default()).unwrap();

        // Verify the OCR font was added to the page resources
        let page = doc.get_page(0).unwrap();
        let fonts = doc.page_fonts(page);
        assert!(
            fonts.contains_key("F_OCR"),
            "Page should have F_OCR font after OCR, got keys: {:?}",
            fonts.keys().collect::<Vec<_>>()
        );

        let text = doc.extract_page_text(0).unwrap_or_default();
        assert!(
            text.contains("ScannedText"),
            "Should extract OCR text from page with existing image content, got: {:?}",
            text
        );
    }

    #[test]
    fn ocr_font_found_on_real_scanned_pdf() {
        // Test with a real scanned PDF (if available) to verify font resolution
        use crate::Document;
        use std::path::Path;

        let path = Path::new("tests/corpus/scanned/graph_scanned.pdf");
        if !path.exists() {
            return;
        }
        let data = std::fs::read(path).unwrap();
        let mut doc = Document::from_bytes(&data).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "TestWord".to_string(),
                x: 100,
                y: 100,
                width: 200,
                height: 30,
                confidence: 0.9,
            }],
        };

        doc.ocr_page(0, &engine, &OcrConfig::default()).unwrap();

        let page = doc.get_page(0).unwrap();
        let fonts = doc.page_fonts(page);
        assert!(
            fonts.contains_key("F_OCR"),
            "Real scanned PDF should have F_OCR after OCR, got keys: {:?}",
            fonts.keys().collect::<Vec<_>>()
        );

        let text = doc.extract_page_text(0).unwrap_or_default();
        assert!(
            text.contains("TestWord"),
            "Should extract mock OCR text from real scanned PDF, got: {:?}",
            text
        );
    }

    #[test]
    fn ocr_all_pages_counts_correctly() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap(); // blank (will be OCR'd)
        doc.add_page(612.0, 792.0).unwrap(); // blank (will be OCR'd)

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "Word".to_string(),
                x: 50,
                y: 50,
                width: 100,
                height: 25,
                confidence: 0.8,
            }],
        };
        let config = OcrConfig::default();

        let count = doc.ocr_all_pages(&engine, &config).unwrap();
        assert_eq!(count, 2, "Should OCR both blank pages");
    }

    #[test]
    fn redo_ocr_replaces_existing_ocr_text() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();

        // First OCR pass
        let engine1 = MockOcrEngine {
            words: vec![OcrWord {
                text: "FirstPass".to_string(),
                x: 100,
                y: 100,
                width: 200,
                height: 40,
                confidence: 0.9,
            }],
        };
        doc.ocr_page(0, &engine1, &OcrConfig::default()).unwrap();

        let text1 = doc.extract_page_text(0).unwrap_or_default();
        assert!(text1.contains("FirstPass"), "First OCR should work");

        // Redo OCR with different text
        let engine2 = MockOcrEngine {
            words: vec![OcrWord {
                text: "SecondPass".to_string(),
                x: 100,
                y: 100,
                width: 200,
                height: 40,
                confidence: 0.95,
            }],
        };
        let config = OcrConfig {
            should_redo: true,
            ..Default::default()
        };
        let applied = doc.redo_ocr_page(0, &engine2, &config).unwrap();
        assert!(applied, "Redo should apply");

        let text2 = doc.extract_page_text(0).unwrap_or_default();
        assert!(
            text2.contains("SecondPass"),
            "Redo should produce new text, got: {:?}",
            text2
        );
        assert!(
            !text2.contains("FirstPass"),
            "Old OCR text should be gone, got: {:?}",
            text2
        );
    }

    #[test]
    fn ocr_rotated_page_produces_text() {
        use crate::Document;

        let mut doc = Document::new();
        doc.add_page(612.0, 792.0).unwrap();
        doc.rotate_page(0, 90).unwrap();

        let engine = MockOcrEngine {
            words: vec![OcrWord {
                text: "Rotated".to_string(),
                x: 100,
                y: 100,
                width: 200,
                height: 40,
                confidence: 0.9,
            }],
        };

        let applied = doc.ocr_page(0, &engine, &OcrConfig::default()).unwrap();
        assert!(applied);

        let text = doc.extract_page_text(0).unwrap_or_default();
        assert!(
            text.contains("Rotated"),
            "Rotated page OCR should work, got: {:?}",
            text
        );
    }
}

// --- Document integration ---

use crate::core::objects::{Dictionary, Object, PdfName};
use crate::document::Document;
use crate::error::{PdfError, PdfResult};
use crate::rendering::{RenderOptions, Renderer};

impl Document {
    /// Runs OCR on a single page and overlays invisible text.
    ///
    /// Renders the page, runs the OCR engine, and appends an invisible
    /// text layer (rendering mode 3) that makes the page searchable
    /// and accessible to screen readers.
    ///
    /// Returns `Ok(true)` if OCR was applied, `Ok(false)` if skipped
    /// (page already has text and `config.skip_text_pages` is set).
    pub fn ocr_page(
        &mut self,
        page_index: usize,
        engine: &dyn OcrEngine,
        config: &OcrConfig,
    ) -> PdfResult<bool> {
        // Skip pages that already have text
        if config.skip_text_pages {
            if let Ok(text) = self.extract_page_text(page_index) {
                if !text.trim().is_empty() {
                    return Ok(false);
                }
            }
        }

        // Get page dimensions
        let page = self.get_page(page_index)?;
        let media_box = self.page_media_box(page)?;
        let page_width = media_box[2] - media_box[0];
        let page_height = media_box[3] - media_box[1];

        // Render the page at OCR DPI
        let renderer = Renderer::new(
            self,
            RenderOptions {
                dpi: config.dpi,
                ..Default::default()
            },
        );
        let pixmap = renderer.render_page(page_index)?;

        // Convert to grayscale
        let grayscale = pixmap_to_grayscale(&pixmap);

        // Optionally preprocess (contrast + binarization)
        let ocr_image = if config.preprocess {
            preprocess::preprocess_for_ocr(&grayscale)
        } else {
            grayscale
        };

        // Run OCR
        let result = engine.recognize(&ocr_image)?;
        if result.words.is_empty() {
            return Ok(false);
        }

        // Generate invisible text layer with ToUnicode CMap
        let layer = text_layer::build_ocr_text_layer(&result, page_width, page_height, config);

        // Create OCR font with ToUnicode CMap for full Unicode support
        let mut font_dict = Dictionary::new();
        font_dict.insert(PdfName::new("Type"), Object::Name(PdfName::new("Font")));
        font_dict.insert(PdfName::new("Subtype"), Object::Name(PdfName::new("Type1")));
        font_dict.insert(
            PdfName::new("BaseFont"),
            Object::Name(PdfName::new("Helvetica")),
        );

        // Attach ToUnicode CMap if present (enables correct Unicode extraction)
        if let Some(cmap_stream) = layer.to_unicode_cmap {
            let cmap_id = self.add_object(Object::Stream(cmap_stream));
            font_dict.insert(
                PdfName::new("ToUnicode"),
                Object::Reference(crate::core::objects::IndirectRef::new(cmap_id.0, cmap_id.1)),
            );
        }

        let mut fonts = Dictionary::new();
        fonts.insert(PdfName::new(OCR_FONT_NAME), Object::Dictionary(font_dict));

        // Append to page
        self.append_content_stream(page_index, &layer.content, Some(fonts))?;

        // Build tagged PDF structure (StructTreeRoot, Document → P/H elements)
        crate::accessibility::structure_builder::add_tagged_structure_from_ocr(
            self,
            page_index,
            &result,
            &config.language,
        )?;

        Ok(true)
    }

    /// Runs OCR on all image-only pages in the document.
    ///
    /// Returns the number of pages that were OCR'd.
    pub fn ocr_all_pages(
        &mut self,
        engine: &dyn OcrEngine,
        config: &OcrConfig,
    ) -> PdfResult<usize> {
        let page_count = self.page_count()?;
        let mut ocr_count = 0;

        for i in 0..page_count {
            if self.ocr_page(i, engine, config)? {
                ocr_count += 1;
            }
        }

        Ok(ocr_count)
    }

    /// Strips existing OCR content and re-runs OCR on a page.
    ///
    /// Removes the OCR content stream (identified by the `F_OCR` font)
    /// and the `F_OCR` font resource, then runs OCR fresh. Use this when
    /// a previous OCR pass produced poor results and you want to try
    /// with a different engine or settings.
    pub fn redo_ocr_page(
        &mut self,
        page_index: usize,
        engine: &dyn OcrEngine,
        config: &OcrConfig,
    ) -> PdfResult<bool> {
        self.strip_ocr_content(page_index)?;

        // Run OCR without skip_text_pages (we just stripped)
        let mut redo_config = config.clone();
        redo_config.skip_text_pages = false;
        self.ocr_page(page_index, engine, &redo_config)
    }

    /// Removes OCR-generated content from a page.
    ///
    /// Finds and removes content streams that reference `F_OCR` font,
    /// and removes the `F_OCR` entry from the page's font resources.
    fn strip_ocr_content(&mut self, page_index: usize) -> PdfResult<()> {
        let page_id = self.page_object_id(page_index)?;

        // Get the page's /Contents
        let page = self
            .get_object(page_id)
            .and_then(|o| o.as_dict())
            .ok_or_else(|| PdfError::InvalidStructure("Page is not a dictionary".to_string()))?;

        let contents = page.get(&PdfName::new("Contents")).cloned();

        // Pre-build PdfName keys to avoid repeated allocations
        let ocr_font_name = text_layer::OCR_FONT_NAME;
        let contents_key = PdfName::new("Contents");
        let resources_key = PdfName::new("Resources");
        let font_key = PdfName::new("Font");
        let ocr_font_key = PdfName::new(ocr_font_name);

        // Check if a content stream references the OCR font.
        // Falls back to raw data if decode fails — the F_OCR string
        // is plain ASCII and visible even in compressed data.
        let is_ocr_stream = |stream: &crate::core::objects::PdfStream| -> bool {
            let data = stream.decode_data().unwrap_or_else(|_| stream.data.clone());
            String::from_utf8_lossy(&data).contains(ocr_font_name)
        };

        // Collect non-OCR content stream refs
        let mut keep_ids: Vec<Object> = Vec::new();
        match contents {
            Some(Object::Array(refs)) => {
                keep_ids.reserve(refs.len());
                for r in &refs {
                    if let Object::Reference(iref) = r {
                        let is_ocr = self
                            .get_object(iref.id())
                            .and_then(|o| o.as_stream())
                            .is_some_and(is_ocr_stream);
                        if !is_ocr {
                            keep_ids.push(r.clone());
                        }
                    }
                }
            }
            Some(Object::Reference(r)) => {
                let is_ocr = self
                    .get_object(r.id())
                    .and_then(|o| o.as_stream())
                    .is_some_and(is_ocr_stream);
                if !is_ocr {
                    keep_ids.push(Object::Reference(r));
                }
            }
            _ => {}
        }

        // Update page /Contents
        let page_dict = self
            .get_object_mut(page_id)
            .and_then(|o| {
                if let Object::Dictionary(d) = o {
                    Some(d)
                } else {
                    None
                }
            })
            .ok_or_else(|| PdfError::InvalidStructure("Page is not a dictionary".to_string()))?;

        match keep_ids.len() {
            0 => {
                page_dict.remove(&contents_key);
            }
            1 => {
                page_dict.insert(contents_key.clone(), keep_ids.remove(0));
            }
            _ => {
                page_dict.insert(contents_key.clone(), Object::Array(keep_ids));
            }
        }

        // Remove F_OCR from font resources (handles both indirect and inline)
        let res_ref = page_dict.get(&resources_key).cloned();
        if let Some(Object::Reference(r)) = res_ref {
            if let Some(Object::Dictionary(res)) = self.get_object_mut(r.id()) {
                if let Some(Object::Dictionary(fonts)) = res.get_mut(&font_key) {
                    fonts.remove(&ocr_font_key);
                }
            }
        } else {
            let page_dict = self
                .get_object_mut(page_id)
                .and_then(|o| {
                    if let Object::Dictionary(d) = o {
                        Some(d)
                    } else {
                        None
                    }
                })
                .ok_or_else(|| PdfError::InvalidStructure("Page dict lost".to_string()))?;
            if let Some(Object::Dictionary(res)) = page_dict.get_mut(&resources_key) {
                if let Some(Object::Dictionary(fonts)) = res.get_mut(&font_key) {
                    fonts.remove(&ocr_font_key);
                }
            }
        }

        Ok(())
    }
}