flpdf 0.9.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
//! Construct and initialize [`Pdf`] values from empty, file, and memory inputs.
//!
//! qpdf correspondence: QPDF.cc document-construction entry points (`emptyPDF()`, `processFile()`, and `processMemoryFile()`) and their shared construction orchestration.
//!

// Used by the public factory API's intra-doc links.
#[allow(unused_imports)]
use crate::error::EncryptedError;
use crate::reader::resolver::{ResolverHandle, ResolverWarningOptions};
use crate::reader::{PdfOpenOptions, ReopenableFile};
use crate::xref::{load_xref_state_from_source, XrefLoadOptions};
#[allow(unused_imports)]
use crate::{Error, ObjectHandle, QpdfErrorCode, QpdfExc, XrefForm};
use crate::{Pdf, Result};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Seek};
use std::path::Path;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Convert a terminal canonical open parse failure into qpdf's public
/// `QPDFExc` shape before attaching the warnings collected by `QPDF::warn`.
/// qpdf keeps the source filename and the signed offset on the exception, so
/// callers such as the qtest C-API adapter do not have to reconstruct them
/// from a rendered Rust parse string.
fn qpdf_open_parse_error(description: &[u8], error: Error) -> Error {
    let Error::Parse { offset, message } = error else {
        return error;
    };
    let object = match message.as_str() {
        "trailer dictionary lacks /Size key"
        | "/Size key in trailer dictionary is not an integer"
        | "/Prev key in trailer dictionary is not an integer" => b"trailer".as_slice(),
        "xref syntax invalid" => b"xref table".as_slice(),
        message if message.starts_with("invalid xref entry") => b"xref table".as_slice(),
        _ => b"".as_slice(),
    };
    Error::QpdfExc(QpdfExc::new(
        QpdfErrorCode::DamagedPdf,
        description,
        object,
        i64::try_from(offset).unwrap_or(i64::MAX),
        message.into_bytes(),
    ))
}

static NEXT_PDF_ID: AtomicU64 = AtomicU64::new(1);

impl<R: Read + Seek> Pdf<R> {
    /// Construct qpdf's default, unprocessed document.
    ///
    /// qpdf's `QPDF()` leaves both its trailer and input source uninitialized;
    /// `emptyPDF()` is a separate operation that processes a canonical empty
    /// file (`libqpdf/QPDF.cc:198-213,278-293`). This constructor preserves
    /// that distinction. The resolver owns an explicit invalid input-source
    /// state, so construction does not require a byte buffer or a sentinel
    /// reader.
    pub fn uninitialized() -> Self {
        let unique_id = NEXT_PDF_ID.fetch_add(1, Ordering::Relaxed);
        let resolver = ResolverHandle::new_uninitialized(
            ResolverWarningOptions::new(crate::QPDFLogger::default_logger(), false, Vec::new()),
            unique_id,
        );
        let encryption = resolver.encryption_parameters();
        Self {
            unique_id,
            resolver,
            input_source_control: None,
            version: String::new(),
            parsed: false,
            check_mode: false,
            trailer: ObjectHandle::uninitialized(),
            first_xref_item_offset: 0,
            uncompressed_after_compressed: false,
            foreign_object_maps: BTreeMap::new(),
            foreign_object_to_copy: BTreeMap::new(),
            foreign_page_copy_orders: BTreeMap::new(),
            writer_object_order: None,
            foreign_object_visiting: BTreeMap::new(),
            acroform_cache: Rc::new(RefCell::new(None)),
            trailer_handle_memo: None,
            root_handle_memo: None,
            ever_called_get_all_pages: false,
            ever_pushed_inherited_attributes_to_pages: false,
            page_list_cache: None,
            encryption,
            encryption_inspection: Rc::new(RefCell::new(None)),
        }
    }

    /// Open a document with qpdf's default recovery policy.
    ///
    /// qpdf enables recovery by default. Use [`Pdf::open_with_options`] with
    /// `repair: false` for the explicit strict/suppressed-recovery route.
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_with_options`] (called with qpdf's
    /// default recovery options): [`Error::Io`] / [`Error::Parse`] /
    /// [`Error::Missing`] from loading the cross-reference and trailer, and
    /// [`Error::Encrypted`] when the document is encrypted and cannot be
    /// authenticated.
    pub fn open(reader: R) -> Result<Self> {
        Self::open_with_options(reader, PdfOpenOptions::default())
    }

    /// Open a document with qpdf-style xref/trailer recovery explicitly enabled.
    ///
    /// This is equivalent to [`Pdf::open`] because qpdf enables recovery by
    /// default. Diagnostics from the recovery pass are stored on the handle and
    /// exposed via [`Pdf::repair_diagnostics`].
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_with_options`] (called with `repair`
    /// enabled); see that method for the full error set.
    pub fn open_with_repair(reader: R) -> Result<Self> {
        Self::open_with_options(
            reader,
            PdfOpenOptions {
                repair: true,
                ..PdfOpenOptions::default()
            },
        )
    }

    /// Alias for [`Pdf::open_with_repair`].
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_with_repair`].
    pub fn open_best_effort(reader: R) -> Result<Self> {
        Self::open_with_repair(reader)
    }

    /// Open a document with explicit repair and password options.
    ///
    /// # Errors
    ///
    /// - [`Error::QpdfExc`] when the cross-reference table or trailer is
    ///   malformed. The exception carries qpdf's filename, object description,
    ///   offset and message.
    /// - [`Error::Io`] / [`Error::Missing`] for the remaining load failures
    ///   (an unreadable stream, or a cross-reference stream missing its
    ///   `/Size` or `/W` entry).
    /// - [`Error::OpenFailure`] wrapping any of the above when diagnostics
    ///   were collected before the failure, including with `repair` unset.
    ///   Use [`Error::open_failure`] to reach both the terminal error and
    ///   those diagnostics. With `options.repair` set, the qpdf-style recovery
    ///   pass runs first and only its residual failures surface.
    /// - [`Error::Unsupported`] when a cross-reference stream uses an unsupported
    ///   entry type or `/W` field-width layout.
    /// - [`Error::Encrypted`] when the document carries an `/Encrypt` dictionary
    ///   that cannot be authenticated or processed: a wrong password
    ///   ([`EncryptedError::BadPassword`]), an unsupported filter or revision
    ///   ([`EncryptedError::UnsupportedHandler`]), a structurally invalid
    ///   `/Encrypt` dictionary ([`EncryptedError::Malformed`]). Weak
    ///   encryption is readable; qpdf's `--allow-weak-crypto` is a write-only
    ///   policy.
    pub fn open_with_options(reader: R, options: PdfOpenOptions) -> Result<Self> {
        Self::open_with_repair_mode(reader, options, false)
    }

    /// Open a document for qpdf's read-only encryption inspection path.
    ///
    /// Unlike [`Pdf::open_with_options`], this retains the parsed encryption
    /// parameters and returns a document when password authentication fails
    /// with [`EncryptedError::BadPassword`]. The returned document is only
    /// suitable for encryption inspection; its authenticated decryption state
    /// remains absent.
    pub fn open_for_encryption_inspection(reader: R, options: PdfOpenOptions) -> Result<Self> {
        Self::open_with_repair_mode(reader, options, true)
    }

    fn open_with_repair_mode(
        reader: R,
        options: PdfOpenOptions,
        allow_bad_password: bool,
    ) -> Result<Self> {
        Self::open_with_repair_mode_as(reader, options, allow_bad_password, None)
    }

    /// The open path with an optional pre-assigned document identity.
    ///
    /// `QPDF::processMemoryFile` installs a source on an already constructed
    /// `QPDF`, so every handle minted while parsing must carry that object's
    /// identity rather than a fresh one; `None` allocates a new identity for
    /// the ordinary factory functions.
    fn open_with_repair_mode_as(
        reader: R,
        options: PdfOpenOptions,
        allow_bad_password: bool,
        unique_id: Option<u64>,
    ) -> Result<Self> {
        let warning_options = ResolverWarningOptions::new(
            options
                .logger
                .clone()
                .unwrap_or_else(crate::QPDFLogger::default_logger),
            options.suppress_warnings,
            options.description.clone(),
        );
        let unique_id = unique_id.unwrap_or_else(|| NEXT_PDF_ID.fetch_add(1, Ordering::Relaxed));
        let resolver = ResolverHandle::new_shared(
            reader,
            0,
            BTreeMap::new(),
            options.repair,
            false,
            crate::Diagnostics::default(),
            warning_options.clone(),
            unique_id,
        );
        let loaded_state = match load_xref_state_from_source(
            resolver.as_ref(),
            XrefLoadOptions {
                ignore_xref_streams: options.ignore_xref_streams,
                description: options.description.clone(),
            },
        ) {
            Ok(state) => state,
            Err(error @ Error::Parse { .. }) => {
                let error = qpdf_open_parse_error(&options.description, error);
                return Err(Error::with_open_diagnostics(
                    error,
                    resolver.repair_diagnostics(),
                ));
            }
            Err(error @ Error::QpdfExc(_)) => {
                return Err(Error::with_open_diagnostics(
                    error,
                    resolver.repair_diagnostics(),
                ));
            }
            // These are terminal xref-load failures raised after the canonical
            // owner has already collected earlier qpdf warnings. Keep the
            // logger-delivery Error::System path below unwrapped: qpdf's
            // warning sink failure is a caller-channel failure, not a failed
            // PDF open (`QPDF::warn`, libqpdf/QPDF.cc:487-504).
            Err(error @ (Error::Io(_) | Error::Missing(_))) => {
                return Err(Error::with_open_diagnostics(
                    error,
                    resolver.repair_diagnostics(),
                ));
            }
            Err(error) => return Err(error),
        };
        // The xref loader updates this resolver's QPDF::Members-shaped xref
        // registration and trailer as each section is read. The returned
        // LoadedXrefState carries derived open metadata; it is not reinstalled
        // as a second authoritative xref table here.
        let parsed_xref_streams = loaded_state.parsed_xref_streams;
        let trailer_references = loaded_state.trailer_references;
        let first_xref_item_offset = loaded_state.first_xref_item_offset;
        let uncompressed_after_compressed = loaded_state.uncompressed_after_compressed;
        let classic_trailer_offset = loaded_state.classic_trailer_offset;
        let loaded = loaded_state.loaded;
        // QPDF's parser registers indirect references while reading every
        // trailer, including historical /Prev sections (QPDFParser.cc:168-175).
        // Canonical xref loading has already minted those handles in this
        // resolver; retain this idempotent registration for trailer
        // references collected during recovery.
        for object_ref in trailer_references {
            if object_ref.number != 0 && object_ref.generation != u16::MAX {
                resolver.get_object_handle(object_ref);
            }
        }
        // qpdf's readTrailer resets InputSource::last_offset to the beginning
        // of the classic trailer before initializeEncryption
        // (`QPDF.cc:1313-1327`). An xref-stream trailer is the stream object
        // itself, so retain the live stream read position for later lazy
        // resolution diagnostics.
        if matches!(loaded.last_xref_form, XrefForm::Table) {
            resolver.set_last_offset(
                classic_trailer_offset
                    .map(|offset| offset as u64)
                    .unwrap_or(loaded.startxref),
            );
        }
        let trailer = loaded.trailer;
        // `Pdf::encryption` is the same `Rc<RefCell<..>>` allocation as
        // `ResolverCore::encryption_parameters` (qpdf's `m->encp`), not a
        // separate copy kept in sync.
        let encryption = resolver.encryption_parameters();
        let mut pdf = Self {
            unique_id,
            resolver,
            input_source_control: None,
            version: loaded.version,
            parsed: true,
            check_mode: false,
            trailer,
            first_xref_item_offset,
            uncompressed_after_compressed,
            foreign_object_maps: BTreeMap::new(),
            foreign_object_to_copy: BTreeMap::new(),
            foreign_page_copy_orders: BTreeMap::new(),
            writer_object_order: None,
            foreign_object_visiting: BTreeMap::new(),
            acroform_cache: Rc::new(RefCell::new(None)),
            trailer_handle_memo: None,
            root_handle_memo: None,
            ever_called_get_all_pages: false,
            ever_pushed_inherited_attributes_to_pages: false,
            page_list_cache: None,
            encryption,
            encryption_inspection: Rc::new(RefCell::new(None)),
        };
        pdf.install_parsed_xref_stream_handles(parsed_xref_streams)?;
        let encryption_inspection = match pdf.initialize_encryption_inspection() {
            Ok(inspection) => inspection,
            Err(error) => {
                // Same diagnostic-wrapping boundary as the authentication
                // failure below: xref recovery may have already recorded repair
                // warnings, and a suppressed inspection consumer (such as the
                // JSON check route, which replays them via
                // `Error::OpenFailure`/`report_open_failure`) must not lose them
                // just because a malformed `/Encrypt` entry fails this
                // password-independent parse before authentication even runs.
                let diagnostics = pdf.repair_diagnostics();
                return Err(Error::with_open_diagnostics(error, diagnostics));
            }
        };
        if let Some(inspection) = encryption_inspection.as_ref() {
            if let Err(error) = pdf.authenticate_if_encrypted(&options, inspection) {
                // qpdf reconstructs and records warnings before
                // `initializeEncryption` (`libqpdf/QPDF.cc:450-471`) and raises
                // authentication errors afterward (`libqpdf/QPDF_encryption.cc:929`).
                // Preserve that warning stream alongside the terminal
                // password/encryption error so file-backed helpers can emit it
                // before the final diagnostic.
                if allow_bad_password
                    && matches!(error, Error::Encrypted(EncryptedError::BadPassword))
                {
                    return Ok(pdf);
                }
                let diagnostics = pdf.repair_diagnostics();
                return Err(Error::with_open_diagnostics(error, diagnostics));
            }
        }
        Ok(pdf)
    }
}

impl Pdf<Cursor<Arc<[u8]>>> {
    /// Open a PDF document from a shared, reference-counted byte buffer.
    ///
    /// **This call copies nothing.** The document and the caller share one
    /// allocation; clone the `Arc` to keep reading the same bytes elsewhere,
    /// and it is freed once both are done with it. (Producing the `Arc<[u8]>`
    /// in the first place may copy — `Vec<u8> -> Arc<[u8]>` reallocates so the
    /// refcount can sit beside the data — but that happens once, in the
    /// caller's own code, not per open.)
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use flpdf::Pdf;
    ///
    /// let bytes: Arc<[u8]> = std::fs::read("input.pdf")?.into();
    /// let kept = Arc::clone(&bytes);
    /// let mut pdf = Pdf::open_mem(bytes)?;
    /// // `kept` and the document are the same bytes, not two copies.
    /// println!("version {} over {} shared bytes", pdf.version(), kept.len());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Why `Arc<[u8]>` and not `&[u8]`
    ///
    /// This took `&[u8]` and returned `Pdf<Cursor<&'a [u8]>>`, borrowing
    /// without copying. That type is no longer well-formed: `Pdf<R>` requires
    /// `R: 'static` (see the bound on [`Pdf`] for why), so the input must be
    /// owned rather than borrowed.
    ///
    /// Copying the slice internally would have kept the old signature, and it
    /// is the wrong trade. qpdf's own in-memory entry point does not copy:
    /// `QPDF::processMemoryFile` (`libqpdf/QPDF.cc:259-268`) wraps the
    /// caller's pointer in a `BufferInputSource` over
    /// `Buffer(unsigned char*, size_t)`, whose contract is "memory is owned by
    /// the caller and will not be freed when the Buffer is destroyed"
    /// (`include/qpdf/Buffer.hh:42-45`). Shared ownership is the safe-Rust
    /// analogue of that contract — no copy on either side — and a caller who
    /// holds only a slice writes `Arc::from(slice)` itself, so the copy is
    /// visible at the call site rather than hidden in the library.
    ///
    /// `Arc` rather than `Rc` because the buffer, unlike the document, can then
    /// be shared across threads that each open their own `Pdf`. The `Arc` buys
    /// sharing of the *input*, not of the document — the two doctests below
    /// pin both halves of that, so neither can go stale silently.
    ///
    /// One buffer, cloned across threads, each clone opening its own document:
    ///
    /// ```
    /// use std::sync::Arc;
    /// use flpdf::Pdf;
    ///
    /// let bytes: Arc<[u8]> = Arc::from(&b"%PDF-1.4\n"[..]);
    /// let workers: Vec<_> = (0..2)
    ///     .map(|_| {
    ///         let shared = Arc::clone(&bytes);
    ///         std::thread::spawn(move || Pdf::open_mem(shared).is_ok())
    ///     })
    ///     .collect();
    /// for worker in workers {
    ///     worker.join().unwrap();
    /// }
    /// ```
    ///
    /// The document itself, by contrast, is not `Send`, and has not been since
    /// long before the resolver existed: `handle_registry` holds
    /// [`ObjectHandle`]s whose identity is `Rc<RefCell<..>>`, as that field's
    /// own comment records. The resolver's `Rc` is a second reason, not the
    /// reason — compiling the snippet below standalone reports both, and
    /// `Rc<RefCell<DirectSlot>>` is the one that predates this work.
    /// `compile_fail` passes on *any* error,
    /// so this one is only meaningful next to the example above: that one
    /// builds the same `Arc<[u8]>` and calls the same `open_mem`, and it runs.
    /// The bound `require_send` adds is therefore the only thing left to
    /// reject:
    ///
    /// ```compile_fail
    /// use std::sync::Arc;
    /// use flpdf::Pdf;
    ///
    /// fn require_send<T: Send>(_: T) {}
    /// let bytes: Arc<[u8]> = Arc::from(&b"%PDF-1.4\n"[..]);
    /// require_send(Pdf::open_mem(bytes));
    /// ```
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open`]; see that method for the full error set.
    pub fn open_mem(bytes: Arc<[u8]>) -> crate::Result<Self> {
        Self::open(Cursor::new(bytes))
    }

    /// Open a PDF document from a shared byte buffer with explicit open options.
    ///
    /// Like [`Pdf::open_mem`] but accepts a [`PdfOpenOptions`] struct for repair and
    /// password configuration, mirroring [`Pdf::open_with_options`]. Shares
    /// `bytes` without copying, on the same terms.
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_with_options`]; see that method for the
    /// full error set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use flpdf::{Pdf, PdfOpenOptions};
    ///
    /// let bytes: Arc<[u8]> = std::fs::read("input.pdf")?.into();
    /// let opts = PdfOpenOptions { repair: true, ..PdfOpenOptions::default() };
    /// let mut pdf = Pdf::open_mem_with_options(bytes, opts)?;
    /// println!("version {}", pdf.version());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_mem_with_options(bytes: Arc<[u8]>, options: PdfOpenOptions) -> crate::Result<Self> {
        Self::open_with_options(Cursor::new(bytes), options)
    }
}

impl Pdf<Cursor<Vec<u8>>> {
    /// Process an in-memory PDF through an already constructed document.
    ///
    /// This is qpdf's `QPDF::processMemoryFile` (`include/qpdf/QPDF.hh:91-97`,
    /// `libqpdf/QPDF.cc:259-269`). The Rust document owns the replacement
    /// byte vector, while the qpdf policy state that is observable before the
    /// parse — recovery, warning suppression, logger, and source description
    /// — is carried across to the normal opening path. A failed parse leaves
    /// the existing document unchanged, just as qpdf does not install a new
    /// parsed source until its process call succeeds.
    pub fn process_memory_file(
        &mut self,
        description: impl AsRef<[u8]>,
        bytes: Vec<u8>,
    ) -> crate::Result<()> {
        if self.parsed {
            return Err(crate::Error::Internal(
                "QPDF::processMemoryFile must be called before a process method".to_owned(),
            ));
        }
        let options = PdfOpenOptions {
            repair: self.resolver.attempt_recovery(),
            logger: Some(self.resolver.logger()),
            suppress_warnings: self.resolver.suppress_warnings(),
            description: description.as_ref().to_vec(),
            ..PdfOpenOptions::default()
        };
        // Parse with this document's identity so the handles minted during
        // the open (trailer, root, cached objects) and any handle created
        // afterwards agree on their owner.
        *self = Self::open_with_repair_mode_as(
            Cursor::new(bytes),
            options,
            false,
            Some(self.unique_id),
        )?;
        Ok(())
    }

    /// Open a PDF document from an owned byte vector without wrapping it in a `Cursor` manually.
    ///
    /// The sole-ownership counterpart to [`Pdf::open_mem`]: the handle takes the
    /// `Vec` outright rather than sharing an `Arc`. Neither copies; both are
    /// `'static` and can be freely moved and stored in data structures.
    ///
    /// This is the preferred form for in-memory PDF handling in most contexts (e.g. WASM,
    /// test helpers, fulgur's document pipeline).
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open`]; see that method for the full error set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use flpdf::Pdf;
    ///
    /// let bytes: Vec<u8> = std::fs::read("input.pdf")?;
    /// let mut pdf = Pdf::open_mem_owned(bytes)?;
    /// println!("version {}", pdf.version());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_mem_owned(bytes: Vec<u8>) -> crate::Result<Self> {
        Self::open(Cursor::new(bytes))
    }

    /// Open a PDF document from an owned byte vector with explicit open options.
    ///
    /// Like [`Pdf::open_mem_owned`] but accepts a [`PdfOpenOptions`] struct for repair
    /// and password configuration, mirroring [`Pdf::open_with_options`].
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_with_options`]; see that method for the
    /// full error set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use flpdf::{Pdf, PdfOpenOptions};
    ///
    /// let bytes: Vec<u8> = std::fs::read("input.pdf")?;
    /// let opts = PdfOpenOptions { repair: true, ..PdfOpenOptions::default() };
    /// let mut pdf = Pdf::open_mem_owned_with_options(bytes, opts)?;
    /// println!("version {}", pdf.version());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_mem_owned_with_options(
        bytes: Vec<u8>,
        options: PdfOpenOptions,
    ) -> crate::Result<Self> {
        Self::open_with_options(Cursor::new(bytes), options)
    }
}

impl Pdf<Box<dyn crate::ReadSeek>> {
    /// Open a path through qpdf's reopenable file-source boundary.
    ///
    /// The returned erased document is suitable for a mixed qpdf page job:
    /// its source can be closed and reopened by the page-spec create stage
    /// (`QPDFJob::create_qpdf`) without exposing a concrete reader type to the
    /// caller. The source is initially kept open so the opening parse can
    /// complete; the job selects the final policy before resolving page
    /// specifications.
    ///
    /// This corresponds to `QPDF::processFile` plus
    /// `ClosedFileInputSource::before`/`after`
    /// (`libqpdf/QPDF.cc:244-249`, `libqpdf/ClosedFileInputSource.cc:18-35`).
    pub fn open_file_with_options(
        path: impl AsRef<Path>,
        options: PdfOpenOptions,
    ) -> crate::Result<Self> {
        let path = path.as_ref();
        let source = ReopenableFile::new(path)
            .map_err(|error| crate::Error::file_io("open", path.to_path_buf(), error))?;
        let controller = source.controller();
        let mut pdf = Self::open_with_options(Box::new(source), options)?;
        pdf.input_source_control = Some(controller);
        Ok(pdf)
    }
}

// Mirrors qpdf's `EMPTY_PDF` (`libqpdf/QPDF.cc:34-51`) byte for byte: PDF
// 1.3, a Catalog (object 1) pointing at an empty Pages tree (object 2), and
// a classic xref table whose offsets match this exact literal.
pub(crate) const EMPTY_PDF_BYTES: &[u8] = concat!(
    "%PDF-1.3\n",
    "1 0 obj\n",
    "<< /Type /Catalog /Pages 2 0 R >>\n",
    "endobj\n",
    "2 0 obj\n",
    "<< /Type /Pages /Kids [] /Count 0 >>\n",
    "endobj\n",
    "xref\n",
    "0 3\n",
    "0000000000 65535 f \n",
    "0000000009 00000 n \n",
    "0000000058 00000 n \n",
    "trailer << /Size 3 /Root 1 0 R >>\n",
    "startxref\n",
    "110\n",
    "%%EOF\n",
)
.as_bytes();

/// Open qpdf's canonical empty document through the erased source boundary
/// used by [`crate::job::JobDocument`].
pub(crate) fn open_empty_with_options_erased(
    options: PdfOpenOptions,
) -> crate::Result<Pdf<Box<dyn crate::ReadSeek>>> {
    Pdf::<Box<dyn crate::ReadSeek>>::open_with_options(
        Box::new(Cursor::new(EMPTY_PDF_BYTES.to_vec())),
        options,
    )
}

impl Pdf<Cursor<Vec<u8>>> {
    // qpdf's `QPDF::emptyPDF()` is a `void` method that initializes an already-
    // constructed `QPDF` with the canonical empty bytes. `Pdf::uninitialized`
    // preserves the separate default-constructed state, while `empty()` is
    // the ready-to-use factory for qpdf's `emptyPDF()` result.
    /// Open a canonical minimal PDF: a `Catalog` (object 1) pointing at an
    /// empty `Pages` tree (object 2, zero pages), read through the normal
    /// parser and object cache like any other document.
    ///
    /// Mirrors qpdf's `QPDF::emptyPDF()` (`libqpdf/QPDF.cc:34-51,290-293`):
    /// the same fixed bytes, opened the same way [`Pdf::open_mem_owned`]
    /// opens any in-memory PDF. Objects can be added and the trailer or
    /// catalog mutated exactly as with any other opened document.
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Pdf::open_mem_owned`]; the fixed bytes
    /// are well-formed, so in practice this only surfaces allocator or
    /// similar infrastructure failures.
    ///
    /// # Examples
    ///
    /// ```
    /// use flpdf::Pdf;
    ///
    /// let pdf = Pdf::empty()?;
    /// assert_eq!(pdf.version(), "1.3");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn empty() -> crate::Result<Self> {
        // qpdf's QPDF::emptyPDF() reads the canonical bytes through
        // processMemoryFile("empty PDF", ...), so warnings raised by this
        // document carry the same source description
        // (`libqpdf/QPDF.cc:290-293`).
        let options = PdfOpenOptions {
            description: b"empty PDF".to_vec(),
            ..PdfOpenOptions::default()
        };
        Self::open_mem_owned_with_options(EMPTY_PDF_BYTES.to_vec(), options)
    }
}

#[cfg(test)]
mod tests {
    use super::{qpdf_open_parse_error, Pdf, EMPTY_PDF_BYTES};
    use crate::reader::resolver::{ResolverHandle, ResolverWarningOptions};
    use crate::xref::{load_xref_state_from_source, XrefLoadOptions};
    use crate::{Error, ObjectRef, PdfOpenOptions, QPDFLogger};
    use std::collections::BTreeMap;
    use std::io::{Cursor, Read, Seek, SeekFrom};

    #[test]
    fn classic_trailer_children_are_canonical_before_open_handoff() {
        let unique_id = 0x12_34_56;
        let resolver = ResolverHandle::new_shared(
            Cursor::new(EMPTY_PDF_BYTES.to_vec()),
            0,
            BTreeMap::new(),
            true,
            false,
            crate::Diagnostics::default(),
            ResolverWarningOptions::new(QPDFLogger::default_logger(), false, Vec::new()),
            unique_id,
        );
        let loaded = load_xref_state_from_source(resolver.as_ref(), XrefLoadOptions::default())
            .expect("classic xref should load through the canonical owner");

        let trailer_root = loaded
            .loaded
            .trailer
            .try_get_key(b"/Root")
            .expect("trailer /Root lookup");
        let cached_root = resolver.get_object_handle(ObjectRef::new(1, 0));
        assert!(
            trailer_root.is_same_object_as(&cached_root),
            "classic trailer indirect children must be the canonical cache slot"
        );
        assert_eq!(trailer_root.owning_pdf_unique_id(), Some(unique_id));
    }

    #[test]
    fn initial_seek_failure_is_not_reported_as_a_read_failure() {
        struct SeekFails;

        // cov:ignore-start: the test reader's seek always fails before any read can occur
        impl Read for SeekFails {
            fn read(&mut self, _buffer: &mut [u8]) -> std::io::Result<usize> {
                unreachable!("the initial seek must fail before a read");
            }
        }
        // cov:ignore-end

        impl Seek for SeekFails {
            fn seek(&mut self, _position: SeekFrom) -> std::io::Result<u64> {
                Err(std::io::Error::other("initial seek failed"))
            }
        }

        let options = PdfOpenOptions {
            description: b"input.pdf".to_vec(),
            ..Default::default()
        };
        let error = Pdf::open_with_options(SeekFails, options)
            .err()
            .expect("the initial seek failure must abort opening");

        assert!(matches!(error, Error::Io(error) if error.to_string() == "initial seek failed"));
    }

    #[test]
    fn qpdf_open_parse_error_leaves_non_parse_errors_untouched() {
        let error = Error::Internal("already canonical".to_owned());

        assert!(matches!(
            qpdf_open_parse_error(b"input.pdf", error),
            Error::Internal(message) if message == "already canonical"
        ));
    }

    #[test]
    fn strict_open_wraps_a_canonical_qpdf_exception() {
        let mut bytes = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n".to_vec();
        let xref = bytes.len();
        bytes.extend_from_slice(b"xref\n0 2\n0000000000 65535 f \n000000000x 00000 n \n");
        bytes.extend_from_slice(
            format!("trailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
        );

        let error = Pdf::open_with_options(
            Cursor::new(bytes),
            PdfOpenOptions {
                repair: false,
                description: b"bad5.pdf".to_vec(),
                ..PdfOpenOptions::default()
            },
        )
        .err()
        .expect("strict open must reject a malformed classic xref entry");
        assert!(matches!(
            error,
            Error::QpdfExc(exception)
                if exception.get_filename() == b"bad5.pdf"
                    && exception.get_object() == b"xref table"
                    && exception.get_message_detail() == b"invalid xref entry (obj=1)"
        ));
    }

    #[test]
    fn uninitialized_memory_processing_honors_strict_recovery_policy() {
        let mut pdf = Pdf::uninitialized();
        pdf.set_attempt_recovery(false);
        pdf.set_suppress_warnings(true);

        let error = pdf
            .process_memory_file(b"empty", Vec::new())
            .expect_err("an empty strict input must fail at the qpdf parse boundary");

        assert!(!pdf.resolver.attempt_recovery());
        let (source, diagnostics) = error
            .open_failure()
            .expect("strict qpdf parse must retain the header warning");
        assert!(matches!(
            source,
            Error::QpdfExc(exception)
                if exception.get_message_detail() == b"can't find startxref"
        ));
        assert_eq!(diagnostics.entries().len(), 1);
        assert_eq!(
            diagnostics.entries()[0].get_message_detail(),
            b"can't find PDF header"
        );
        assert!(pdf.suppress_warnings());
    }

    #[test]
    fn memory_processing_rejects_reprocessing_a_parsed_document() {
        let mut pdf = Pdf::empty().expect("empty PDF should open");
        let _trailer = pdf.trailer();

        let error = pdf
            .process_memory_file(b"replacement", Vec::new())
            .expect_err("qpdf process methods are pre-parse operations");

        assert!(
            matches!(error, Error::Internal(message) if message == "QPDF::processMemoryFile must be called before a process method")
        );
    }

    #[test]
    fn memory_processing_installs_a_successful_source_and_preserves_document_identity() {
        let mut pdf = Pdf::uninitialized();
        let unique_id = pdf.unique_id;

        pdf.process_memory_file(b"empty PDF", EMPTY_PDF_BYTES.to_vec())
            .expect("qpdf memory processing should install a valid source");

        assert!(pdf.parsed);
        assert_eq!(pdf.unique_id, unique_id);
        // Handles minted while parsing and handles created afterwards must
        // share one owner: qpdf's processMemoryFile keeps working on the
        // same QPDF object.
        let root = pdf.root_handle().expect("root resolves");
        let stream = pdf
            .new_stream_with_data(std::rc::Rc::new(b"x".to_vec()))
            .expect("new stream on the processed document");
        root.replace_key(b"/X", stream)
            .expect("a handle minted during the open accepts a later handle of the same document");
    }
}