stet-pdf-reader 0.1.0

PDF parser and renderer
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
// stet-pdf-reader
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! PDF parser, page navigator, and content stream interpreter.
//!
//! `stet-pdf-reader` is a self-contained PDF reader: it opens a PDF, walks
//! its object graph, and interprets each page's content stream into a
//! `stet_graphics::display_list::DisplayList` that any downstream consumer
//! (rasterizer, PDF writer, custom output device) can render.
//!
//! The crate intentionally has **no dependency on `stet-core`** — it uses
//! only `stet-fonts` (font parsing) and `stet-graphics` (display list and
//! ICC types), so it can be used as a standalone PDF parser/renderer
//! without pulling in the PostScript interpreter.
//!
//! # Quick start
//!
//! ```no_run
//! use stet_pdf_reader::PdfDocument;
//!
//! let data = std::fs::read("document.pdf")?;
//! let doc = PdfDocument::from_bytes(&data)?;
//!
//! for page in 0..doc.page_count() {
//!     let display_list = doc.render_page(page, 150.0)?;
//!     // …consume the display list (rasterize, convert, inspect, etc.)
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! With the default `render` feature enabled, [`PdfDocument::render_page_to_rgba`]
//! skips the display-list-handling boilerplate and produces RGBA pixels
//! directly via `stet-render`.
//!
//! # Encrypted PDFs
//!
//! `from_bytes` / `from_bytes_with_icc` try the empty password. If the
//! file uses a non-empty user password they return
//! [`PdfError::PasswordRequired`]; the caller can then prompt the user
//! and retry with [`PdfDocument::from_bytes_with_password`]:
//!
//! ```no_run
//! use stet_pdf_reader::{PdfDocument, PdfError};
//! use stet_graphics::icc::IccCache;
//!
//! let data = std::fs::read("encrypted.pdf")?;
//! let doc = match PdfDocument::from_bytes(&data) {
//!     Ok(doc) => doc,
//!     Err(PdfError::PasswordRequired) => {
//!         let pw = prompt_user_for_password();
//!         PdfDocument::from_bytes_with_password(&data, IccCache::new(), pw.as_bytes())?
//!     }
//!     Err(e) => return Err(e.into()),
//! };
//! # fn prompt_user_for_password() -> String { String::new() }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! RC4 (40/128-bit), AES-128, and AES-256 (R=5/6) are all supported.
//!
//! # Acknowledgements
//!
//! JPEG 2000, JBIG2, and CCITT-Fax stream decoding use the
//! [`hayro-jpeg2000`](https://crates.io/crates/hayro-jpeg2000),
//! [`hayro-jbig2`](https://crates.io/crates/hayro-jbig2), and
//! [`hayro-ccitt`](https://crates.io/crates/hayro-ccitt) crates from the
//! [hayro](https://github.com/LaurenzV/hayro) PDF renderer by Laurenz
//! Stampfl. Big thanks to the hayro project for factoring those decoders
//! out as reusable crates — `stet-pdf-reader` would not cover the full
//! PDF stream-filter surface without them.

pub mod content;
pub mod crypto;
pub mod error;
pub mod filters;
pub mod lexer;
pub mod objects;
pub mod page_tree;
pub mod resolver;
pub mod resources;
pub mod xref;

pub use error::PdfError;
pub use objects::{PdfDict, PdfObj};
pub use page_tree::PageInfo;

use content::ContentInterpreter;
use resolver::Resolver;
use std::collections::HashSet;
use std::sync::Arc;
use stet_fonts::geometry::Matrix;
use stet_graphics::display_list::DisplayList;
use stet_graphics::icc::IccCache;

/// Font data provider: maps a font file name (e.g. "NimbusSans-Regular") to raw .t1 bytes.
///
/// Used for environments without filesystem access (WASM) where fonts are embedded.
pub type FontProvider = Arc<dyn Fn(&str) -> Option<Vec<u8>> + Send + Sync>;

/// A parsed PDF document.
pub struct PdfDocument<'a> {
    resolver: Resolver<'a>,
    pages: Vec<PageInfo>,
    icc_cache: IccCache,
    font_provider: Option<FontProvider>,
    /// When false (default), PDF overprint flags (OP/op) are suppressed —
    /// skips the expensive CMYK buffer simulation that most viewers omit.
    overprint: bool,
    /// Object numbers of Optional Content Groups that are OFF by default.
    /// Parsed from the catalog's /OCProperties /D /OFF array.
    ocg_off: HashSet<u32>,
    /// Decompressed ICC profile bytes from the first /OutputIntents entry's
    /// /DestOutputProfile stream, if present. Used to match the document's
    /// intended CMYK rendering (ISO Coated v2, SWOP, etc.) at render time.
    output_intent_icc: Option<Vec<u8>>,
}

impl<'a> PdfDocument<'a> {
    /// Parse a PDF from bytes.
    pub fn from_bytes(data: &'a [u8]) -> Result<Self, PdfError> {
        let mut icc_cache = IccCache::new();
        icc_cache.search_system_cmyk_profile();
        Self::from_bytes_inner(data, icc_cache, b"")
    }

    /// Parse a PDF from bytes, using a pre-loaded ICC cache.
    ///
    /// Use this when the caller already has an `IccCache` with the system
    /// CMYK profile loaded (e.g., from the PostScript interpreter context).
    pub fn from_bytes_with_icc(data: &'a [u8], icc_cache: IccCache) -> Result<Self, PdfError> {
        Self::from_bytes_inner(data, icc_cache, b"")
    }

    /// Parse a PDF from bytes using a user-supplied password.
    ///
    /// Returns `PdfError::PasswordRequired` if the password does not
    /// match; callers can retry by calling this again with a different
    /// password.
    pub fn from_bytes_with_password(
        data: &'a [u8],
        icc_cache: IccCache,
        password: &[u8],
    ) -> Result<Self, PdfError> {
        Self::from_bytes_inner(data, icc_cache, password)
    }

    fn from_bytes_inner(
        data: &'a [u8],
        icc_cache: IccCache,
        password: &[u8],
    ) -> Result<Self, PdfError> {
        // Validate header — PDF spec allows up to 1024 bytes before %PDF-
        if !has_pdf_header(data) {
            return Err(PdfError::NotAPdf);
        }

        let xref = xref::parse_xref(data)?;

        // Handle encryption. /Encrypt null means no encryption (some
        // generators emit this).
        let encryption = if let Some(encrypt_ref) = xref.trailer.get(b"Encrypt") {
            if matches!(encrypt_ref, crate::objects::PdfObj::Null) {
                None
            } else {
                // Temporary resolver (without encryption) to dereference
                // the Encrypt dict itself.
                let temp_resolver = Resolver::new(data, &xref);
                let encrypt_obj = temp_resolver.deref(encrypt_ref)?;
                let encrypt_dict = encrypt_obj
                    .as_dict()
                    .ok_or(PdfError::Other("Encrypt is not a dict".into()))?;

                let file_id = xref
                    .trailer
                    .get_array(b"ID")
                    .and_then(|arr| arr.first()?.as_str().map(|s| s.to_vec()))
                    .unwrap_or_default();

                Some(crypto::EncryptionState::try_open_with_password(
                    encrypt_dict,
                    &xref.trailer,
                    &file_id,
                    password,
                )?)
            }
        } else {
            None
        };

        let resolver = Resolver::with_encryption(data, xref, encryption);
        let pages = page_tree::collect_pages(&resolver)?;
        let ocg_off = parse_ocg_off(&resolver);
        let output_intent_icc = parse_output_intent_icc(&resolver);

        Ok(Self {
            resolver,
            pages,
            icc_cache,
            font_provider: None,
            overprint: true,
            ocg_off,
            output_intent_icc,
        })
    }

    /// Enable or disable PDF overprint simulation.
    ///
    /// Enabled by default. When disabled, OP/op flags in graphics state dicts
    /// are ignored, avoiding CMYK buffer tracking.
    pub fn set_overprint(&mut self, enabled: bool) {
        self.overprint = enabled;
    }

    /// Set a font data provider for environments without filesystem access.
    pub fn set_font_provider(&mut self, provider: FontProvider) {
        self.font_provider = Some(provider);
    }

    /// Number of pages in the document.
    pub fn page_count(&self) -> usize {
        self.pages.len()
    }

    /// Page dimensions in points (width, height), accounting for rotation.
    pub fn page_size(&self, page: usize) -> Result<(f64, f64), PdfError> {
        let info = self
            .pages
            .get(page)
            .ok_or(PdfError::PageOutOfRange(page, self.pages.len()))?;
        let [llx, lly, urx, ury] = info.crop_box;
        let (w, h) = ((urx - llx).abs(), (ury - lly).abs());
        match info.rotate.rem_euclid(360) {
            90 | 270 => Ok((h, w)),
            _ => Ok((w, h)),
        }
    }

    /// Get page info (MediaBox, CropBox, rotation, resources).
    pub fn page_info(&self, page: usize) -> Result<&PageInfo, PdfError> {
        self.pages
            .get(page)
            .ok_or(PdfError::PageOutOfRange(page, self.pages.len()))
    }

    /// Get the decompressed content stream bytes for a page.
    /// If the page has multiple content streams, they are concatenated
    /// with a newline separator.
    pub fn page_contents(&self, page: usize) -> Result<Vec<u8>, PdfError> {
        let info = self
            .pages
            .get(page)
            .ok_or(PdfError::PageOutOfRange(page, self.pages.len()))?;

        if info.contents.is_empty() {
            return Ok(Vec::new());
        }

        let mut result = Vec::new();
        for (i, &(obj_num, gen_num)) in info.contents.iter().enumerate() {
            // Skip content stream refs that fail (e.g., dict without stream body
            // in malformed PDFs). Continue with remaining streams.
            match self.resolver.stream_data(obj_num, gen_num) {
                Ok(data) => {
                    if i > 0 && !result.is_empty() {
                        result.push(b'\n');
                    }
                    result.extend_from_slice(&data);
                }
                Err(_) => continue,
            }
        }

        Ok(result)
    }

    /// Render a page to a DisplayList at the given DPI.
    ///
    /// The display list uses device-space coordinates (paths pre-transformed
    /// through the initial CTM). The initial CTM applies DPI scaling, Y-flip,
    /// and CropBox offset.
    pub fn render_page(&self, page: usize, dpi: f64) -> Result<DisplayList, PdfError> {
        let info = self
            .pages
            .get(page)
            .ok_or(PdfError::PageOutOfRange(page, self.pages.len()))?;

        let [llx, lly, urx, ury] = info.crop_box;
        let (page_w, page_h) = ((urx - llx).abs(), (ury - lly).abs());

        // Build initial CTM: scale by dpi/72, Y-flip (PDF Y-up → device Y-down),
        // and offset by CropBox origin.
        let scale = dpi / 72.0;
        let ctm = match info.rotate.rem_euclid(360) {
            90 => {
                // Rotate 90° CW + Y-flip: (x,y) → (y*s, x*s)
                Matrix::new(0.0, scale, scale, 0.0, 0.0, 0.0).concat(&Matrix::translate(-llx, -lly))
            }
            180 => {
                // Rotate 180° + Y-flip = just X-flip
                Matrix::new(-scale, 0.0, 0.0, scale, page_w * scale, 0.0)
                    .concat(&Matrix::translate(-llx, -lly))
            }
            270 => {
                // Rotate 270° CW + Y-flip: (x,y) → ((page_h-y)*s, (page_w-x)*s)
                Matrix::new(0.0, -scale, -scale, 0.0, page_h * scale, page_w * scale)
                    .concat(&Matrix::translate(-llx, -lly))
            }
            _ => {
                // No rotation: scale + Y-flip + CropBox offset
                // PDF (0,0) at bottom-left → device (0, page_h*scale) at top-left
                Matrix::new(scale, 0.0, 0.0, -scale, -llx * scale, ury * scale)
            }
        };

        // Get page content stream
        let content_data = self.page_contents(page)?;

        // Interpret content stream
        let mut interpreter = ContentInterpreter::new(
            &self.resolver,
            info.resources.clone(),
            ctm,
            &self.icc_cache,
            self.font_provider.clone(),
            self.overprint,
            &self.ocg_off,
        );

        // Check if the page has a DeviceCMYK transparency group — if so,
        // RGB colors need round-tripping through CMYK to match compositing
        // in CMYK space (mutes saturated out-of-gamut RGB colors).
        let page_group_is_cmyk = if let Ok(page_obj) = self.resolver.resolve(info.obj_num, 0)
            && let Some(page_dict) = page_obj.as_dict()
            && let Some(group_obj) = page_dict.get(b"Group")
            && let Ok(group_resolved) = self.resolver.deref(group_obj)
            && let Some(group_dict) = group_resolved.as_dict()
            && group_dict.get_name(b"CS") == Some(b"DeviceCMYK")
        {
            interpreter.set_page_group_cmyk();
            true
        } else {
            false
        };

        // Render page content
        if let Err(e) = interpreter.interpret_stream_public(&content_data) {
            eprintln!("warning: content stream error: {}", e);
        }
        // Unwind any unbalanced q's left by the content stream.
        interpreter.unwind_gstate_stack();

        // Render annotation appearance streams (form field values, stamps, etc.)
        if !info.annots.is_empty() {
            interpreter.reset_clip_for_annotations();
            for &(n, g) in &info.annots {
                let _ = interpreter.render_annotation(n, g);
            }
        }

        let mut dl = interpreter.into_display_list();
        if page_group_is_cmyk {
            dl.set_page_group_color_space(stet_graphics::display_list::GroupColorSpace::DeviceCMYK);
        }
        Ok(dl)
    }

    /// Render a page to RGBA pixel data at the given DPI.
    ///
    /// Returns (pixel_data, width, height). Pixel data is RGBA, 4 bytes per pixel.
    #[cfg(feature = "render")]
    pub fn render_page_to_rgba(
        &self,
        page: usize,
        dpi: f64,
    ) -> Result<(Vec<u8>, u32, u32), PdfError> {
        let (page_w, page_h) = self.page_size(page)?;
        let scale = dpi / 72.0;
        let pixel_w = (page_w * scale).round() as u32;
        let pixel_h = (page_h * scale).round() as u32;

        let display_list = self.render_page(page, dpi)?;

        let rgba = stet_render::render_to_rgba(
            &display_list,
            pixel_w,
            pixel_h,
            dpi,
            Some(&self.icc_cache),
            false,
        );

        Ok((rgba, pixel_w, pixel_h))
    }

    /// Access the ICC color profile cache.
    pub fn icc_cache(&self) -> &IccCache {
        &self.icc_cache
    }

    /// Decompressed ICC profile bytes from the PDF's OutputIntent, if any.
    /// PDF/X files declare their intended CMYK rendering space here (e.g.
    /// ISO Coated v2 300% (ECI)); using it at render time matches the
    /// document author's colour expectations, which system-default profiles
    /// (GS `default_cmyk.icc`, FOGRA39) often approximate only coarsely.
    pub fn output_intent_icc(&self) -> Option<&[u8]> {
        self.output_intent_icc.as_deref()
    }

    /// Register the PDF's OutputIntent ICC profile as the default CMYK profile
    /// in this document's ICC cache, replacing whatever was loaded from
    /// `search_system_cmyk_profile`. Returns `true` when the profile was
    /// present and registered.
    pub fn apply_output_intent_as_default_cmyk(&mut self) -> bool {
        let Some(bytes) = self.output_intent_icc.as_deref() else {
            return false;
        };
        let Some(hash) = self.icc_cache.register_profile(bytes) else {
            return false;
        };
        self.icc_cache.set_system_cmyk(bytes, hash);
        true
    }

    /// Access the resolver for arbitrary object lookups.
    pub fn resolver(&self) -> &Resolver<'a> {
        &self.resolver
    }

    /// Access page info list.
    pub fn pages(&self) -> &[PageInfo] {
        &self.pages
    }
}

/// Parse the default OFF set from the catalog's OCProperties.
/// Returns a set of object numbers for OCGs that are OFF by default.
/// OCGs not listed in either /ON or /OFF are considered ON (PDF spec default).
fn parse_ocg_off(resolver: &Resolver) -> HashSet<u32> {
    let mut off = HashSet::new();

    // Get catalog — try trailer /Root first, fall back to scanning if it
    // doesn't look like a catalog (corrupt incremental updates can swap
    // /Root and /Info, leaving Root pointing at the Info dict).
    let mut catalog_owned;
    let catalog_dict = if let Some(root_ref) = resolver.trailer().get_ref(b"Root") {
        if let Ok(c) = resolver.resolve(root_ref.0, root_ref.1) {
            catalog_owned = c;
            match catalog_owned.as_dict() {
                Some(d) if d.get(b"OCProperties").is_some() => d,
                _ => match find_catalog(resolver) {
                    Some(c) => {
                        catalog_owned = c;
                        catalog_owned.as_dict().unwrap()
                    }
                    None => return off,
                },
            }
        } else {
            return off;
        }
    } else {
        return off;
    };

    // Get OCProperties -> D (default configuration) -> OFF array
    let oc_props = match catalog_dict.get(b"OCProperties") {
        Some(obj) => match resolver.deref(obj) {
            Ok(o) => o,
            Err(_) => return off,
        },
        None => return off,
    };
    let oc_dict = match oc_props.as_dict() {
        Some(d) => d,
        None => return off,
    };
    let d_obj = match oc_dict.get(b"D") {
        Some(obj) => match resolver.deref(obj) {
            Ok(o) => o,
            Err(_) => return off,
        },
        None => return off,
    };
    let d_dict = match d_obj.as_dict() {
        Some(d) => d,
        None => return off,
    };

    // Collect object numbers from /OFF array (may be an indirect reference)
    if let Some(off_obj) = d_dict.get(b"OFF") {
        let off_resolved = resolver.deref(off_obj).unwrap_or_else(|_| off_obj.clone());
        if let Some(off_arr) = off_resolved.as_array() {
            for obj in off_arr {
                if let Some((num, _gen)) = obj.as_ref() {
                    off.insert(num);
                }
            }
        }
    }

    off
}

/// Extract the decompressed ICC profile bytes from the first PDF/X
/// OutputIntent whose `/DestOutputProfile` is a CMYK ICC stream.
///
/// PDF/X files declare their intended CMYK rendering profile (e.g. "ISO
/// Coated v2 300% (ECI)") via `/Catalog/OutputIntents` with an embedded
/// `/DestOutputProfile` stream. Using that profile at render time matches
/// the author's colour expectations; the system-default profiles used as
/// fallback (GS `default_cmyk.icc`, FOGRA39) only approximate it.
fn parse_output_intent_icc(resolver: &Resolver) -> Option<Vec<u8>> {
    let mut catalog_owned;
    let catalog_dict = if let Some(root_ref) = resolver.trailer().get_ref(b"Root") {
        if let Ok(c) = resolver.resolve(root_ref.0, root_ref.1) {
            catalog_owned = c;
            match catalog_owned.as_dict() {
                Some(d) if d.get(b"OutputIntents").is_some() => d,
                _ => {
                    catalog_owned = find_catalog(resolver)?;
                    catalog_owned.as_dict()?
                }
            }
        } else {
            catalog_owned = find_catalog(resolver)?;
            catalog_owned.as_dict()?
        }
    } else {
        catalog_owned = find_catalog(resolver)?;
        catalog_owned.as_dict()?
    };

    let intents_obj = resolver.deref(catalog_dict.get(b"OutputIntents")?).ok()?;
    let intents_arr = intents_obj.as_array()?;
    for entry in intents_arr {
        let intent = match resolver.deref(entry) {
            Ok(o) => o,
            Err(_) => continue,
        };
        let Some(intent_dict) = intent.as_dict() else {
            continue;
        };
        let Some(profile_obj) = intent_dict.get(b"DestOutputProfile") else {
            continue;
        };
        let Ok(bytes) = resolver.stream_data_from_obj(profile_obj) else {
            continue;
        };
        // ICC header: color space at offset 16, 'acsp' magic at offset 36.
        if bytes.len() >= 40 && &bytes[36..40] == b"acsp" && &bytes[16..20] == b"CMYK" {
            return Some(bytes);
        }
    }
    None
}

/// Scan all objects to find the real Catalog dict (has /Type /Catalog).
/// Used when the trailer's /Root points to the wrong object.
fn find_catalog(resolver: &Resolver) -> Option<PdfObj> {
    let xref_len = resolver.xref_len();
    for obj_num in 0..xref_len as u32 {
        if let Ok(obj) = resolver.resolve(obj_num, 0) {
            if let Some(dict) = obj.as_dict() {
                if dict.get_name(b"Type") == Some(b"Catalog") && dict.get(b"Pages").is_some() {
                    return Some(obj);
                }
            }
        }
    }
    None
}

/// Check for `%PDF-` header within the first 1024 bytes.
/// The PDF spec (§7.5.2) allows data before the header.
fn has_pdf_header(data: &[u8]) -> bool {
    let search_range = data.len().min(1024);
    data[..search_range].windows(5).any(|w| w == b"%PDF-")
}

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

    #[test]
    fn not_a_pdf() {
        let result = PdfDocument::from_bytes(b"not a pdf");
        assert!(matches!(result, Err(PdfError::NotAPdf)));
    }

    #[test]
    fn parse_minimal_pdf() {
        let pdf = build_minimal_pdf();
        let doc = PdfDocument::from_bytes(&pdf).unwrap();
        assert_eq!(doc.page_count(), 1);

        let (w, h) = doc.page_size(0).unwrap();
        assert_eq!(w, 612.0);
        assert_eq!(h, 792.0);
    }

    #[test]
    fn page_out_of_range() {
        let pdf = build_minimal_pdf();
        let doc = PdfDocument::from_bytes(&pdf).unwrap();
        assert!(matches!(
            doc.page_size(5),
            Err(PdfError::PageOutOfRange(5, 1))
        ));
    }

    #[test]
    fn page_contents_empty() {
        let pdf = build_minimal_pdf();
        let doc = PdfDocument::from_bytes(&pdf).unwrap();
        let contents = doc.page_contents(0).unwrap();
        // Our minimal PDF has no content stream
        assert!(contents.is_empty());
    }

    #[test]
    #[ignore]
    fn dump_display_list() {
        use stet_fonts::geometry::PsPath;
        use stet_graphics::display_list::{DisplayElement, DisplayList};

        fn path_bbox(path: &PsPath) -> String {
            use stet_fonts::geometry::PathSegment;
            let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
            for seg in &path.segments {
                let pts: Vec<(f64, f64)> = match seg {
                    PathSegment::MoveTo(x, y) | PathSegment::LineTo(x, y) => vec![(*x, *y)],
                    PathSegment::CurveTo {
                        x1,
                        y1,
                        x2,
                        y2,
                        x3,
                        y3,
                    } => vec![(*x1, *y1), (*x2, *y2), (*x3, *y3)],
                    PathSegment::ClosePath => vec![],
                };
                for (px, py) in pts {
                    x0 = x0.min(px);
                    y0 = y0.min(py);
                    x1 = x1.max(px);
                    y1 = y1.max(py);
                }
            }
            format!("bbox=({:.0},{:.0},{:.0},{:.0})", x0, y0, x1, y1)
        }

        fn dump(list: &DisplayList, depth: usize) {
            let indent = "  ".repeat(depth);
            for (i, elem) in list.elements().iter().enumerate() {
                match elem {
                    DisplayElement::Fill { path, params } => {
                        let c = &params.color;
                        let cmyk_str = if let Some((c2, m, y, k)) = params.color.native_cmyk {
                            format!(" cmyk=({:.2},{:.2},{:.2},{:.2})", c2, m, y, k)
                        } else {
                            String::new()
                        };
                        eprintln!(
                            "{indent}[{i}] Fill rgb=({:.2},{:.2},{:.2}){} op={} opm={} ch=0x{:x} a={:.2} {}",
                            c.r,
                            c.g,
                            c.b,
                            cmyk_str,
                            params.overprint,
                            params.overprint_mode,
                            params.painted_channels,
                            params.alpha,
                            path_bbox(path)
                        );
                    }
                    DisplayElement::Stroke { path, params } => {
                        let c = &params.color;
                        eprintln!(
                            "{indent}[{i}] Stroke rgb=({:.2},{:.2},{:.2}) {}",
                            c.r,
                            c.g,
                            c.b,
                            path_bbox(path)
                        );
                    }
                    DisplayElement::Clip { path, .. } => {
                        eprintln!("{indent}[{i}] Clip {}", path_bbox(path))
                    }
                    DisplayElement::InitClip => eprintln!("{indent}[{i}] InitClip"),
                    DisplayElement::Image { params, .. } => {
                        eprintln!("{indent}[{i}] Image {}x{}", params.width, params.height);
                    }
                    DisplayElement::ErasePage => eprintln!("{indent}[{i}] ErasePage"),
                    DisplayElement::AxialShading { params } => {
                        eprintln!(
                            "{indent}[{i}] AxialShading cs={:?} stops={}",
                            params.color_space,
                            params.color_stops.len()
                        );
                    }
                    DisplayElement::RadialShading { params } => {
                        eprintln!(
                            "{indent}[{i}] RadialShading cs={:?} stops={} ext=({},{}) c0=({:.1},{:.1}) r0={:.1} c1=({:.1},{:.1}) r1={:.1} bbox={:?} op={} ch=0x{:x}",
                            params.color_space,
                            params.color_stops.len(),
                            params.extend_start,
                            params.extend_end,
                            params.x0,
                            params.y0,
                            params.r0,
                            params.x1,
                            params.y1,
                            params.r1,
                            params.bbox,
                            params.overprint,
                            params.painted_channels
                        );
                        // Print first and last stop
                        if let Some(first) = params.color_stops.first() {
                            eprintln!(
                                "{indent}  stop[0]: pos={:.3} rgb=({:.3},{:.3},{:.3}) raw={:?}",
                                first.position,
                                first.color.r,
                                first.color.g,
                                first.color.b,
                                first.raw_components
                            );
                        }
                        if let Some(last) = params.color_stops.last() {
                            eprintln!(
                                "{indent}  stop[{}]: pos={:.3} rgb=({:.3},{:.3},{:.3}) raw={:?}",
                                params.color_stops.len() - 1,
                                last.position,
                                last.color.r,
                                last.color.g,
                                last.color.b,
                                last.raw_components
                            );
                        }
                        // Print mid stop
                        let mid = params.color_stops.len() / 2;
                        if mid > 0 && mid < params.color_stops.len() - 1 {
                            let s = &params.color_stops[mid];
                            eprintln!(
                                "{indent}  stop[{mid}]: pos={:.3} rgb=({:.3},{:.3},{:.3}) raw={:?}",
                                s.position, s.color.r, s.color.g, s.color.b, s.raw_components
                            );
                        }
                    }
                    DisplayElement::MeshShading { .. } => eprintln!("{indent}[{i}] MeshShading"),
                    DisplayElement::PatchShading { .. } => eprintln!("{indent}[{i}] PatchShading"),
                    DisplayElement::PatternFill { .. } => eprintln!("{indent}[{i}] PatternFill"),
                    DisplayElement::Text { .. } => eprintln!("{indent}[{i}] Text"),
                    DisplayElement::Group { elements, params } => {
                        eprintln!(
                            "{indent}[{i}] Group iso={} ko={} blend={} a={:.2} bbox=({:.0},{:.0},{:.0},{:.0}) children={}",
                            params.isolated,
                            params.knockout,
                            params.blend_mode,
                            params.alpha,
                            params.bbox[0],
                            params.bbox[1],
                            params.bbox[2],
                            params.bbox[3],
                            elements.len()
                        );
                        dump(elements, depth + 1);
                    }
                    DisplayElement::SoftMasked {
                        mask,
                        content,
                        params,
                        ..
                    } => {
                        eprintln!(
                            "{indent}[{i}] SoftMasked {:?} mask={} content={}",
                            params.subtype,
                            mask.len(),
                            content.len()
                        );
                        eprintln!("{indent}  MASK:");
                        dump(mask, depth + 2);
                        eprintln!("{indent}  CONTENT:");
                        dump(content, depth + 2);
                    }
                    DisplayElement::OcgGroup {
                        elements,
                        ocg_id,
                        default_visible,
                    } => {
                        eprintln!(
                            "{indent}[{i}] OcgGroup id={} visible={} children={}",
                            ocg_id,
                            default_visible,
                            elements.len()
                        );
                        dump(elements, depth + 1);
                    }
                }
            }
        }

        let data = std::fs::read("../../pdf_samples/PDFX-ready_Output-Test_X4.pdf").unwrap();
        let doc = PdfDocument::from_bytes(&data).unwrap();
        let dl = doc.render_page(0, 72.0).unwrap();
        eprintln!("=== Display list: {} top-level elements ===", dl.len());
        dump(&dl, 0);
    }

    /// Build a minimal valid PDF for testing.
    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend(b"%PDF-1.4\n");

        // Object 1: Catalog
        let obj1_offset = pdf.len();
        pdf.extend(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        // Object 2: Pages
        let obj2_offset = pdf.len();
        pdf.extend(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        // Object 3: Page
        let obj3_offset = pdf.len();
        pdf.extend(b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n");

        // Xref
        let xref_offset = pdf.len();
        pdf.extend(b"xref\n0 4\n");
        pdf.extend(b"0000000000 65535 f\r\n");
        pdf.extend(format!("{:010} 00000 n\r\n", obj1_offset).as_bytes());
        pdf.extend(format!("{:010} 00000 n\r\n", obj2_offset).as_bytes());
        pdf.extend(format!("{:010} 00000 n\r\n", obj3_offset).as_bytes());
        pdf.extend(b"trailer\n<< /Size 4 /Root 1 0 R >>\n");
        pdf.extend(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());

        pdf
    }
}