Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Never crash: bound the allocations behind the nightly fuzz runner's out-of-memory deaths

Brandon Thomas1449b71a198b
diff --git a/Cargo.lock b/Cargo.lock
index 54f21b884..7a0bfb32e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2704,8 +2704,6 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lopdf"
version = "0.45.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3"
dependencies = [
"aes",
"bitflags 2.13.2",
diff --git a/Cargo.toml b/Cargo.toml
index 238095f3c..28e32d019 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -87,3 +87,4 @@ codegen-units = 1
hayro-interpret = { path = "vendor/hayro-interpret" }
hayro = { path = "vendor/hayro" }
hayro-syntax = { path = "vendor/hayro-syntax" }
+lopdf = { path = "vendor/lopdf" }
diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rs
index 279e8b9fa..3b2c906c5 100644
--- a/crates/cos/src/document.rs
+++ b/crates/cos/src/document.rs
@@ -763,11 +763,14 @@ impl Document {
Some(a) => a.iter().filter_map(Object::as_int).collect(),
None => vec![0, size],
};
- let raw = s.decoded()?;
let row = w[0] + w[1] + w[2];
if row == 0 {
return Err(CosError::Syntax { offset: off, detail: "xref stream row width 0".into() });
}
+ // One row per object, and a document has at most 8,388,607 indirect objects (the classic
+ // implementation limit): decoding more than that (about 200 MB at the widest rows) is a
+ // decompression bomb, not cross-reference data. The section is then reconstructed.
+ let raw = s.decoded_within(MAX_XREF_OBJECTS.saturating_mul(row))?;
let field = |r: &[u8], from: usize, len: usize, default: u64| -> u64 {
if len == 0 {
return default;
@@ -908,6 +911,10 @@ fn generated_id(seed: &[u8; 32]) -> Vec<u8> {
out
}
+/// The most indirect objects a document can have (the classic implementation limit, ISO
+/// 32000-1 Annex C): it bounds how much data a cross-reference stream can hold.
+const MAX_XREF_OBJECTS: usize = 8_388_607;
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1050,4 +1057,29 @@ mod tests {
assert!(!doc.repair_log().is_empty());
assert_eq!(doc.root(), Some(ObjRef::new(1, 0)));
}
+
+ #[test]
+ fn a_decompression_bomb_in_an_xref_stream_is_refused_and_the_file_reconstructed() {
+ // 32 MiB of rows behind two FlateDecode filters (a few hundred bytes in the file) for
+ // /W [1 1 1]: at 3 bytes a row that is more than 8,388,607 objects' worth, so it is not
+ // decoded (in full: the limit applies while inflating) and the objects are found by
+ // reconstruction instead.
+ let bomb = printcraft_filters::encode_flate(&printcraft_filters::encode_flate(&vec![0u8; 32 << 20]));
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let o1 = bytes.len();
+ bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ let o2 = bytes.len();
+ bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
+ let x = bytes.len();
+ bytes.extend_from_slice(
+ format!("3 0 obj\n<< /Type /XRef /Size 4 /W [1 1 1] /Root 1 0 R /Filter [/FlateDecode /FlateDecode] /Length {} >>\nstream\n", bomb.len())
+ .as_bytes(),
+ );
+ bytes.extend_from_slice(&bomb);
+ bytes.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{x}\n%%EOF\n").as_bytes());
+ assert!(o1 < o2 && o2 < x);
+ let doc = Document::open(Arc::new(bytes)).unwrap();
+ assert_eq!(doc.root(), Some(ObjRef::new(1, 0)));
+ assert!(doc.repair_log().iter().any(|l| l.contains("limit")), "{:?}", doc.repair_log());
+ }
}
diff --git a/crates/cos/src/object.rs b/crates/cos/src/object.rs
index cf1d0bf9b..96eac347c 100644
--- a/crates/cos/src/object.rs
+++ b/crates/cos/src/object.rs
@@ -215,11 +215,17 @@ impl Stream {
/// decoded before the damage is returned). Streams with image codecs fail with
/// `CosError::Filter` (keep them encoded). Use `decoded_strict` to detect damage.
pub fn decoded(&self) -> Result<Vec<u8>, CosError> {
+ self.decoded_within(MAX_DECODED)
+ }
+
+ /// Like [`Stream::decoded`], for a stream whose decoded size has a tighter bound than
+ /// [`MAX_DECODED`]: decoding past `max` bytes is an error.
+ pub fn decoded_within(&self, max: usize) -> Result<Vec<u8>, CosError> {
let chain = self.filters();
if chain.is_empty() {
return Ok(self.raw.as_ref().clone());
}
- printcraft_filters::decode_tolerant(&chain, &self.raw, MAX_DECODED).map(|(v, _)| v).map_err(|e| CosError::Filter(e.to_string()))
+ printcraft_filters::decode_tolerant(&chain, &self.raw, max.min(MAX_DECODED)).map(|(v, _)| v).map_err(|e| CosError::Filter(e.to_string()))
}
/// Decoded data; any corruption is an error.
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index 279cf7c9f..04351c9ca 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -16,6 +16,15 @@ use lopdf::{Dictionary, Document, LoadOptions, Object, ObjectId};
use crate::OpenError;
+/// lopdf decodes object and cross-reference streams while it loads, with no limit unless one is
+/// set: a few hundred bytes of nested FlateDecode then inflate to gigabytes. Real object and
+/// xref streams are far below this.
+const LOAD_STREAM_LIMIT: usize = 256 << 20;
+
+fn load_options(password: Option<&str>) -> LoadOptions {
+ LoadOptions { password: password.map(str::to_owned), max_decompressed_size: Some(LOAD_STREAM_LIMIT), ..LoadOptions::default() }
+}
+
#[derive(Clone, Debug, Default)]
pub struct DocInfo {
pub title: Option<String>,
@@ -249,7 +258,7 @@ pub fn inspect(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocInfo, O
Ok(p) => info.pages = p,
Err(p) => return Err(OpenError::Invalid(format!("the page tree could not be read: {}", crate::raster::panic_message(&p)))),
}
- let options = LoadOptions { password: password.map(str::to_owned), ..LoadOptions::default() };
+ let options = load_options(password);
let structure = catch_unwind(AssertUnwindSafe(|| match Document::load_mem_with_options(&bytes, options) {
Ok(doc) => {
let mut tmp = DocInfo::default();
@@ -854,7 +863,7 @@ pub fn pretty_date(s: &str) -> String {
/// Fetch an attachment's bytes (decoded). Capped at 1 GiB to defuse decompression bombs.
pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -> Result<Vec<u8>, String> {
let run = || -> Result<Vec<u8>, String> {
- let options = LoadOptions { password: password.map(str::to_owned), ..LoadOptions::default() };
+ let options = load_options(password);
let doc = Document::load_mem_with_options(bytes, options).map_err(|e| e.to_string())?;
let insp = Inspector::new(&doc);
let spec: &Object = match &att.source {
@@ -886,6 +895,16 @@ pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -
#[cfg(test)]
mod tests {
+ #[test]
+ fn png_predictor_rows_longer_than_the_data_are_refused_before_allocating() {
+ // Vendored lopdf patch: a fuzzed `/Columns 4294967295` allocated two 4 GiB rows before
+ // reading any data. A row that cannot fit in the data is refused up front.
+ let e = lopdf::filters::png::decode_frame(&[2, 0, 0, 0], 1, 64 << 20).unwrap_err();
+ assert!(e.to_string().contains("longer than the data"), "{e}");
+ // A real frame still decodes: two 3-byte rows, the second Up-filtered.
+ assert_eq!(lopdf::filters::png::decode_frame(&[0, 1, 2, 3, 2, 1, 1, 1], 1, 3).unwrap(), [1, 2, 3, 2, 3, 4]);
+ }
+
#[test]
fn view_and_user_space_round_trip_for_every_rotation() {
for rotation in [0u16, 90, 180, 270] {
diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs
index 925c05277..8d7d86707 100644
--- a/crates/render/src/raster.rs
+++ b/crates/render/src/raster.rs
@@ -745,6 +745,41 @@ trailer << /Root 1 0 R >>
assert!(plain.rgba.as_chunks::<4>().0.iter().any(|p| p[0] < 128), "a normal Type 3 glyph still paints");
}
+ /// From `cargo xtask fuzz`: a tiling pattern whose /XStep and /YStep dwarf its /BBox got a
+ /// cell pixmap of `step × scale` pixels, bounded only by u16 (2 GB and more). The vendored
+ /// hayro patch `tiling_cell_scale` keeps the cell within 3000 pixels a side.
+ #[test]
+ fn tiling_cells_stay_small_whatever_the_step() {
+ assert_eq!(hayro::tiling_cell_scale(2.0, 10.0, 3000.0), 2.0, "ordinary cells keep their scale");
+ for step in [1.0e5f32, -1.0e5, 4.0e9] {
+ let s = hayro::tiling_cell_scale(2.0, step, 3000.0);
+ assert!(s * step.abs() <= 3000.5, "{step}: {s}");
+ }
+ assert_eq!(hayro::tiling_cell_scale(2.0, f32::INFINITY, 3000.0), 2.0);
+ assert_eq!(hayro::tiling_cell_scale(2.0, 0.0, 3000.0), 2.0);
+ // End to end: such a pattern renders, and the page's other content still draws.
+ let content = "/Pattern cs /P1 scn 0 0 40 40 re f 1 0 0 rg 0 0 4 4 re f";
+ let pdf = format!(
+ "%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /Pattern << /P1 5 0 R >> >> >> endobj
+4 0 obj << /Length {} >> stream
+{content}
+endstream endobj
+5 0 obj << /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 100000 /YStep 100000 /Length 20 >> stream
+0 0 1 rg 0 0 10 10 re f
+endstream endobj
+trailer << /Root 1 0 R >>
+%%EOF",
+ content.len()
+ );
+ let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
+ let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 });
+ assert!(page.error.is_none(), "{:?}", page.error);
+ assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255]);
+ }
+
/// From `cargo xtask fuzz`: an inline image claiming /W 4294967295 over four bytes of data
/// hung in resampling (vendored hayro patch: `MAX_IMAGE_PIXELS`).
#[test]
diff --git a/vendor/README.md b/vendor/README.md
index 5c7da3d94..d50098cbc 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -9,7 +9,8 @@ the fix. Vendoring copyleft code is never allowed (plan/adr/0001).
|---|---|---|---|---|
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments) | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields` |
-| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped` |
+| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step` |
+| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows); (2) predictor row widths use saturating arithmetic | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating` |
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process | `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers` |
-Temporary: hayro is the bootstrap renderer (ADR-0004); M2.6 replaces it with our own devices.
+Temporary: hayro is the bootstrap renderer and lopdf the bootstrap inspector (ADR-0004); M2.6 replaces them with our own devices and `cos`/`model`.
diff --git a/vendor/hayro/src/lib.rs b/vendor/hayro/src/lib.rs
index d0637e35f..83ed9dcfe 100644
--- a/vendor/hayro/src/lib.rs
+++ b/vendor/hayro/src/lib.rs
@@ -60,6 +60,8 @@ use vello_cpu::color::palette::css::WHITE;
use vello_cpu::{Level, Pixmap, RenderMode};
mod renderer;
+/// PrintCraft patch: exported for its regression test.
+pub use renderer::tiling_cell_scale;
/// A cache used by the renderer.
///
diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rs
index 013ca3b79..a922cfd82 100644
--- a/vendor/hayro/src/renderer.rs
+++ b/vendor/hayro/src/renderer.rs
@@ -510,6 +510,10 @@ impl Renderer {
};
xs = xs.max(min_x_scale).min(max_x_scale);
ys = ys.max(min_y_scale).min(max_y_scale);
+ // PrintCraft patch: the cell pixmap is `step × scale` pixels, which only the
+ // u16 cast below bounded (a fuzzed /XStep far beyond /BBox gave 65535² cells).
+ xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE);
+ ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE);
let x_step = xs * t.x_step;
let y_step = ys * t.y_step;
@@ -1147,3 +1151,15 @@ fn convert_blend_mode(blend_mode: BlendMode) -> peniko::BlendMode {
peniko::BlendMode::new(mix, Compose::SrcOver)
}
+
+/// PrintCraft patch: the scale for a tiling cell, lowered so that the cell pixmap (`|step| ×
+/// scale` pixels a side) stays within `max_pixels`. Geometry is unchanged (the pattern transform
+/// is derived from the scale); an over-large step only renders at lower resolution.
+pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 {
+ let step = step.abs();
+ if step.is_finite() && step > 0.0 && scale * step > max_pixels {
+ max_pixels / step
+ } else {
+ scale
+ }
+}
diff --git a/vendor/lopdf/.editorconfig b/vendor/lopdf/.editorconfig
new file mode 100644
index 000000000..e0f8ed1c1
--- /dev/null
+++ b/vendor/lopdf/.editorconfig
@@ -0,0 +1,12 @@
+root = true
+
+[*]
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+indent_style = space
+indent_size = 4
+
+[*.{md,pdf}]
+trim_trailing_whitespace = false
diff --git a/vendor/lopdf/.gitattributes b/vendor/lopdf/.gitattributes
new file mode 100644
index 000000000..83463c264
--- /dev/null
+++ b/vendor/lopdf/.gitattributes
@@ -0,0 +1,9 @@
+* text eol=lf
+
+*.rs text diff=rust
+*.toml text diff=toml
+*.pdf binary
+Cargo.lock text
+*.jpg binary
+*.jpeg binary
+*.png binary
diff --git a/vendor/lopdf/.gitignore b/vendor/lopdf/.gitignore
new file mode 100644
index 000000000..ba13bc824
--- /dev/null
+++ b/vendor/lopdf/.gitignore
@@ -0,0 +1,10 @@
+target
+Cargo.lock
+test*.pdf
+*.pdf
+.idea
+*log.txt
+specs
+.DS_Store
+/notes
+ops.txt
\ No newline at end of file
diff --git a/vendor/lopdf/CHANGELOG.md b/vendor/lopdf/CHANGELOG.md
new file mode 100644
index 000000000..d38ec589b
--- /dev/null
+++ b/vendor/lopdf/CHANGELOG.md
@@ -0,0 +1,1750 @@
+<a name="v0.44.0"></a>
+## [v0.44.0](https://github.com/J-F-Liu/lopdf/compare/v0.43.0...v0.44.0) (2026-07-10)
+
+### Add
+
+* Add back assets/test.pdf
+
+### Feat
+
+* Support incremental save of encrypted documents (#522)
+* Bound text extraction against decompression bombs
+* Bound load-time decompression via LoadOptions.max_decompressed_size
+* Bound stream decompression to guard against bombs
+* Make ttf-parser optional behind font_embedding feature
+
+### Fix
+
+* Reject incremental save of encrypted documents (#521)
+* Fix Document::get_toc() dropping entries when outline titles repeat (#517)
+* Add feature flag to font test
+* Only use criterion for non-wasm tests/benches
+
+### Move
+
+* Move resource files in tests to assets
+
+### Refactor
+
+* Make `Document::get_page_content` return `Vec<u8>` since it cannot fail
+
+### Test
+
+* Add tests demonstrating unbounded stream decompression
+
+### CI
+
+* CI skip performance test
+* Actually pass --no-default-features in the no-default-features matrix cell (#510)
+
+<a name="v0.43.0"></a>
+## [v0.43.0](https://github.com/J-F-Liu/lopdf/compare/v0.42.0...v0.43.0) (2026-06-25)
+
+### Feat
+
+* Report encryption status in PdfMetadata
+
+
+<a name="v0.42.0"></a>
+## [v0.42.0](https://github.com/J-F-Liu/lopdf/compare/v0.41.0...v0.42.0) (2026-06-23)
+
+### Feat
+
+* Add Content::decode_strict method for strict parsing
+
+### Fix
+
+* Limit array and dictionary nesting depth
+* Include subsequent ObjStm objects in xref stream range
+* Insert newline between concatenated content streams
+* Consume trailing comments in content streams
+
+### Test
+
+* Escape trailing whitespace in parser tests
+
+
+<a name="v0.41.0"></a>
+## [v0.41.0](https://github.com/J-F-Liu/lopdf/compare/v0.40.0...v0.41.0) (2026-06-04)
+
+### Add
+
+* Add test to reproduce bug with replacing text in non-single character TJ Arrays
+* Add regression test PDF file
+* Add performance tests for document loading and page counting
+
+### Fix
+
+* Fix bug replacing text in non-single character TJ Arrays
+* fix clippy errors
+
+### Implement
+
+* Implement differences mapping
+
+### Release
+
+* Release 0.41
+
+### Removes
+
+* Removes `nom_locate` dependency to fix a performance regression introduced in v0.35.0.
+
+
+<a name="v0.40.0"></a>
+## [v0.40.0](https://github.com/J-F-Liu/lopdf/compare/v0.39.0...v0.40.0) (2026-03-19)
+
+### Fix
+
+* Fix a few warnings.
+* Fix WinAnsiEncoding handling in SimpleEncoding string conversion
+
+### Release
+
+* Release 0.40
+
+### Remove
+
+* Remove an unused dependency.
+
+### Return
+
+* return Option via ok() instead of unwrap() for decode_text_string
+
+### Update
+
+* update src/reader to make clippy happy
+
+### Update
+
+* Update `getrandom` to 0.4 and `rand` to 0.10.
+
+### Upgrade
+
+* Upgrade `wasm-bindgen-test` while we're at it.
+
+
+<a name="v0.39.0"></a>
+## [v0.39.0](https://github.com/J-F-Liu/lopdf/compare/v0.38.0...v0.39.0) (2026-01-16)
+
+### Add
+
+* add tests
+
+### Fix
+
+* fix conditionally compile encrypted metadata tests
+* fix test_metadata and clippy warnings
+* fix readme example ci issue
+* fix clippy ci failed
+
+### Release
+
+* Release 0.39
+
+### Breaking change
+
+
+is_encrypted() now returns false after successful
+decryption. Use was_encrypted() to check original encryption state.
+
+
+<a name="v0.38.0"></a>
+## [v0.38.0](https://github.com/J-F-Liu/lopdf/compare/v0.37.0...v0.38.0) (2026-01-16)
+
+### Apply
+
+* apply fix the warnings
+
+### Inline
+
+* Inline ImageMasks don't need to have a ColorSpace so don't require one.
+
+
+<a name="v0.37.0"></a>
+## [v0.37.0](https://github.com/J-F-Liu/lopdf/compare/v0.36.0...v0.37.0) (2026-01-16)
+
+### Add
+
+* add unicode replace support ([#421](https://github.com/J-F-Liu/lopdf/issues/421))
+
+### Avoid
+
+* Avoid unwrapping object streams when decrypting documents
+
+### Change
+
+* Change remove_object() to only remove the object ([#423](https://github.com/J-F-Liu/lopdf/issues/423))
+
+### Ensure
+
+* Ensure we only encrypt with compliant P-values
+
+### Fix
+
+* fix bug ([#422](https://github.com/J-F-Liu/lopdf/issues/422))
+
+### Fix
+
+* Fix clippy
+* Fix bug by encoding OE, UE and Perms for revision 5
+
+### Implement
+
+* Implement tests to encrypt and decrypt documents
+* Implement tests for the password algorithms
+
+### Improve
+
+* Improve readability by consistently iterating over blocks
+* Improve Length field checks
+
+### Retain
+
+* Retain permission bits
+
+### Set
+
+* Set up WASI CI
+* Set up WASM CI workflow
+
+### Update
+
+* Update changelog
+
+
+<a name="v0.36.0"></a>
+## [v0.36.0](https://github.com/J-F-Liu/lopdf/compare/0.35.0...v0.36.0) (2025-03-15)
+
+### Add
+
+* Add support for Revision 5 ([#401](https://github.com/J-F-Liu/lopdf/issues/401))
+* Add more checks to the encryption/decryption logic ([#399](https://github.com/J-F-Liu/lopdf/issues/399))
+* Add sanity checks for PDF encryption, add examples for decrypting/encrypting PDF files and various bug fixes ([#397](https://github.com/J-F-Liu/lopdf/issues/397))
+* Add encrypt function to crypt filters
+* Add support for jiff and make both chrono and time optional features
+
+### Avoid
+
+* Avoid parsing encrypted object streams early and correctly parse object streams upon decryption ([#385](https://github.com/J-F-Liu/lopdf/issues/385))
+* Avoid decrypting cross-reference streams ([#381](https://github.com/J-F-Liu/lopdf/issues/381))
+
+### Check
+
+* Check if the security handler is the standard one
+
+### Clarify
+
+* Clarify datetime parsing logic using the PDF specification
+
+### Compute
+
+* Compute the file encryption key (revision 6)
+
+### Declare
+
+* Declare and implement crypt filters
+
+### Ensure
+
+* Ensure the document is actually encrypted
+
+### Fix
+
+* Fix unused imports
+* Fix warning for rotate example
+* Fix warnings about nom_parser
+* Fix clippy warning about operator precedence
+* Fix typo in comment
+
+### Gracefully
+
+* Gracefully handle the is_aes check without throwing errors ([#376](https://github.com/J-F-Liu/lopdf/issues/376))
+
+### Handle
+
+* Handle cases where the stream objects override the crypt filter
+
+### Implement
+
+* Implement Document::encrypt() ([#396](https://github.com/J-F-Liu/lopdf/issues/396))
+* Implement password authentication (revision 6)
+* Implement decrypt with and without password sanitization
+* Implement authentication functions
+* Implement password sanitization from string
+* Implement password algorithms 2-7
+* Implement encrypt_object function
+* Implement and use PKCS[#5](https://github.com/J-F-Liu/lopdf/issues/5) padding instead
+* Implement function to parse the available crypt filters
+* Implement 256-bit AES-CBC crypt filter
+* Implement TryFrom rather than TryInto
+
+### Improve
+
+* Improve the AES decryption with some sanity checks ([#383](https://github.com/J-F-Liu/lopdf/issues/383))
+
+### Merge
+
+* Merge remaining algorithms functions into PasswordAlgorithm implementation
+
+### Missing
+
+* Missing import to test
+
+### Only
+
+* Only encode EncryptMetadata when V >= 4 ([#400](https://github.com/J-F-Liu/lopdf/issues/400))
+
+### Provide
+
+* Provide revision-agnostic functions for the password algorithms
+
+### Randomly
+
+* Randomly generate file encryption key for V5 in encrypt example ([#403](https://github.com/J-F-Liu/lopdf/issues/403))
+
+### Recurse
+
+* Recurse into arrays and dictionaries to fully decrypt all strings/streams ([#378](https://github.com/J-F-Liu/lopdf/issues/378))
+
+### Release
+
+* Release 0.36
+
+### Remove
+
+* Remove the old implementation
+* Remove workflow that used to enable the nom_parser feature
+* Remove nom_parser feature
+
+### Reorganize
+
+* Reorganize encryption code
+
+### Sanitize
+
+* Sanitize passwords (revision 6)
+
+### Try
+
+* Try decrypting with an empty password
+
+### Unpack
+
+* Unpack objects after decrypting object streams ([#382](https://github.com/J-F-Liu/lopdf/issues/382))
+
+### Update
+
+* Update to nom 8.0 and nom_locate 5.0 ([#402](https://github.com/J-F-Liu/lopdf/issues/402))
+
+### Update
+
+* update changelog
+
+### Use
+
+* Use a hasher instead of allocating a Vec
+* Use the new implementation to compute the file encryption key
+* Use the default stream and string crypt filter if present
+* Use Unix epoch if time feature is not enabled
+* Use get_deref for the Kids array to handle indirect references ([#379](https://github.com/J-F-Liu/lopdf/issues/379))
+
+### Validate
+
+* Validate encryption dictionary for revision 5 ([#405](https://github.com/J-F-Liu/lopdf/issues/405))
+
+### Validate
+
+* validate binary comment during parsing ([#392](https://github.com/J-F-Liu/lopdf/issues/392))
+
+
+<a name="0.35.0"></a>
+## [0.35.0](https://github.com/J-F-Liu/lopdf/compare/v0.34.0...0.35.0) (2025-01-19)
+
+### Add
+
+* Add test for supported color types in PDF image embedding
+* Add function for text chunks extraction. ([#342](https://github.com/J-F-Liu/lopdf/issues/342))
+
+### Added
+
+* added binary comment as attribute and for load and write. Binary Comment is gonna be important for pdf in A/2, A/3 format. ([#370](https://github.com/J-F-Liu/lopdf/issues/370))
+
+### Allow
+
+* Allow parsing off-spec PDF files with prefixes before the header ([#362](https://github.com/J-F-Liu/lopdf/issues/362))
+
+### Also
+
+* Also accept ASCII85 streams without EOD marker ([#354](https://github.com/J-F-Liu/lopdf/issues/354))
+
+### Fix
+
+* Fix clippy warning
+* Fix incorrect image data handling in PDF content stream
+* Fix BitsPerComponent calculation and improper ColorSpace mapping
+* Fix incorrect color type detection for JPEG images
+* Fix mulitplication overflow in ascii85 decode ([#348](https://github.com/J-F-Liu/lopdf/issues/348))
+* Fix out of memory bug ([#347](https://github.com/J-F-Liu/lopdf/issues/347))
+* Fix addition overflow ([#346](https://github.com/J-F-Liu/lopdf/issues/346))
+* Fix lowercase s of Procset and no space target string(J-F-Liu[#323](https://github.com/J-F-Liu/lopdf/issues/323)) ([#324](https://github.com/J-F-Liu/lopdf/issues/324))
+
+### Ignore
+
+* Ignore space after byte index of startxref ([#371](https://github.com/J-F-Liu/lopdf/issues/371))
+
+### Implement
+
+* Implement ToUnicode for variadic len encodings ([#328](https://github.com/J-F-Liu/lopdf/issues/328))
+
+### Improve
+
+* Improve JPEG processing efficiency by avoiding unnecessary decode ([#345](https://github.com/J-F-Liu/lopdf/issues/345))
+* Improve cmap parsing and internal error handling ([#335](https://github.com/J-F-Liu/lopdf/issues/335))
+
+### Inline
+
+* Inline images ([#356](https://github.com/J-F-Liu/lopdf/issues/356))
+
+### Keep
+
+* keep existing values when extending dictionary ([#322](https://github.com/J-F-Liu/lopdf/issues/322))
+
+### Properly
+
+* Properly support document prefixes ([#365](https://github.com/J-F-Liu/lopdf/issues/365))
+
+### Refactor
+
+* Refactor and optimize image processing logic in xobject.rs
+
+### Release
+
+* Release 0.35
+
+### Remove
+
+* remove misleading Object::as_string ([#350](https://github.com/J-F-Liu/lopdf/issues/350))
+
+### Remove
+
+* Remove superfluous `ref` keyword ([#361](https://github.com/J-F-Liu/lopdf/issues/361))
+* Remove pom parser ([#355](https://github.com/J-F-Liu/lopdf/issues/355))
+* Remove /Prev from trailer ([#333](https://github.com/J-F-Liu/lopdf/issues/333))
+
+### Replace
+
+* Replace debug assert with Result ([#349](https://github.com/J-F-Liu/lopdf/issues/349))
+* Replace unwrap with error handling ([#351](https://github.com/J-F-Liu/lopdf/issues/351))
+
+### Rework
+
+* Rework errors ([#358](https://github.com/J-F-Liu/lopdf/issues/358))
+
+### Specify
+
+* Specify minimum Rust version in Cargo.toml ([#320](https://github.com/J-F-Liu/lopdf/issues/320))
+
+### Support
+
+* Support UTF-16 encoding for bookmark titles with non-ASCII characters ([#364](https://github.com/J-F-Liu/lopdf/issues/364))
+* Support AES encryption and revision 4 ([#343](https://github.com/J-F-Liu/lopdf/issues/343))
+
+### Throw
+
+* Throw error if xref stream cannot be uncompressed ([#339](https://github.com/J-F-Liu/lopdf/issues/339))
+
+### Update
+
+* update changelog
+
+
+<a name="v0.34.0"></a>
+## [v0.34.0](https://github.com/J-F-Liu/lopdf/compare/v0.33.0...v0.34.0) (2024-08-31)
+
+### Add
+
+* Add ASCII85 decoding ([#317](https://github.com/J-F-Liu/lopdf/issues/317))
+* Add text extraction based on ToUnicode cmap ([#314](https://github.com/J-F-Liu/lopdf/issues/314))
+* Add error handling to object stream ([#299](https://github.com/J-F-Liu/lopdf/issues/299))
+* Add PDFDocEncoding ([#296](https://github.com/J-F-Liu/lopdf/issues/296))
+
+### Cleanup
+
+* Cleanup comments and cargo fmt ([#290](https://github.com/J-F-Liu/lopdf/issues/290))
+
+### Detect
+
+* Detect reference cycles when going through trailers ([#308](https://github.com/J-F-Liu/lopdf/issues/308))
+* Detect reference cycles when parsing streams (with nom_parser) ([#300](https://github.com/J-F-Liu/lopdf/issues/300))
+* Detect reference cycles when collecting page resources ([#298](https://github.com/J-F-Liu/lopdf/issues/298))
+
+### Fix
+
+* Fix unicode fonts extraction in extract text example. ([#315](https://github.com/J-F-Liu/lopdf/issues/315))
+* Fix clippy warings
+
+### Implement
+
+* Implement encoding and decoding of text strings (PDF1.7 section 7.9.2.2) ([#297](https://github.com/J-F-Liu/lopdf/issues/297))
+
+### Improve
+
+* Improve error handling ([#307](https://github.com/J-F-Liu/lopdf/issues/307))
+
+### Refactor
+
+* Refactor get_or_create_resources() ([#291](https://github.com/J-F-Liu/lopdf/issues/291))
+
+### Release
+
+* Release 0.34
+
+### Replace
+
+* Replace unwrap with returning error ([#310](https://github.com/J-F-Liu/lopdf/issues/310))
+* Replace LinkedHashMap with IndexMap ([#293](https://github.com/J-F-Liu/lopdf/issues/293))
+
+### Update
+
+* Update dependencies ([#309](https://github.com/J-F-Liu/lopdf/issues/309))
+* Update readme of pdfutil ([#295](https://github.com/J-F-Liu/lopdf/issues/295))
+
+
+<a name="v0.33.0"></a>
+## [v0.33.0](https://github.com/J-F-Liu/lopdf/compare/v0.32.0...v0.33.0) (2024-08-31)
+
+### Accept
+
+* Accept comments in content parsing ([#261](https://github.com/J-F-Liu/lopdf/issues/261))
+
+### Added
+
+* Added a new feature to get images info from the pdf page. ([#275](https://github.com/J-F-Liu/lopdf/issues/275))
+
+### Async
+
+* Async Examples ([#266](https://github.com/J-F-Liu/lopdf/issues/266))
+
+### AsyncReader
+
+* AsyncReader ([#265](https://github.com/J-F-Liu/lopdf/issues/265))
+
+### Fix
+
+* Fix parse outline failed, the key ’D‘ might be an object id ([#274](https://github.com/J-F-Liu/lopdf/issues/274))
+* Fix parse outline failed([#270](https://github.com/J-F-Liu/lopdf/issues/270)) ([#271](https://github.com/J-F-Liu/lopdf/issues/271))
+
+### Indexmap
+
+* indexmap use in TOC for sorted TOC ([#267](https://github.com/J-F-Liu/lopdf/issues/267))
+
+### Release
+
+* Release 0.33
+
+### Replace
+
+* Replace md5 with md-5 ([#272](https://github.com/J-F-Liu/lopdf/issues/272))
+
+
+<a name="v0.32.0"></a>
+## [v0.32.0](https://github.com/J-F-Liu/lopdf/compare/v0.31.0...v0.32.0) (2024-08-31)
+
+### Add
+
+* Add debug format for hexadecimal ([#240](https://github.com/J-F-Liu/lopdf/issues/240))
+
+### Added
+
+* Added big generation value parsing ([#257](https://github.com/J-F-Liu/lopdf/issues/257))
+
+### Added
+
+* added object parse to get_page_fonts ([#249](https://github.com/J-F-Liu/lopdf/issues/249))
+* added meta info decryption ([#237](https://github.com/J-F-Liu/lopdf/issues/237))
+
+### Fix
+
+* Fix clippy warning and format code
+* Fix clippy warnings
+* Fix typo in README.md ([#251](https://github.com/J-F-Liu/lopdf/issues/251))
+
+### Fixed
+
+* Fixed parsing of the PDFs with incorrect xrefs to indirect objects ([#254](https://github.com/J-F-Liu/lopdf/issues/254))
+
+### Fixed
+
+* fixed clippy issues ([#238](https://github.com/J-F-Liu/lopdf/issues/238))
+
+### Handle
+
+* Handle references to arrays in get_page_contents() ([#245](https://github.com/J-F-Liu/lopdf/issues/245))
+
+### Object
+
+* Object and related types implement PartialEq ([#236](https://github.com/J-F-Liu/lopdf/issues/236))
+
+### Release
+
+* Release 0.32
+
+
+<a name="v0.31.0"></a>
+## [v0.31.0](https://github.com/J-F-Liu/lopdf/compare/v0.30.0...v0.31.0) (2023-05-10)
+
+### Add
+
+* Add example of page rotation ([#230](https://github.com/J-F-Liu/lopdf/issues/230))
+* Add decryption of documents using RC4 encryption. ([#228](https://github.com/J-F-Liu/lopdf/issues/228))
+
+### Annotate
+
+* Annotate feature usage ([#229](https://github.com/J-F-Liu/lopdf/issues/229))
+
+### Fix
+
+* Fix typo in README.md ([#233](https://github.com/J-F-Liu/lopdf/issues/233))
+
+### PDF
+
+* PDF 2.0 is now a free specification
+
+### Release
+
+* Release 0.31
+
+### Remove
+
+* Remove extraneous `Q` operation from insert_image ([#227](https://github.com/J-F-Liu/lopdf/issues/227))
+
+
+<a name="v0.30.0"></a>
+## [v0.30.0](https://github.com/J-F-Liu/lopdf/compare/v0.29.0...v0.30.0) (2023-04-09)
+
+### Add
+
+* Add support for extracting TOC, Outlines and NamedDestinations ([#211](https://github.com/J-F-Liu/lopdf/issues/211))
+* Add example extract_text ([#212](https://github.com/J-F-Liu/lopdf/issues/212))
+* Add get_encrypted and is_encrypted ([#210](https://github.com/J-F-Liu/lopdf/issues/210))
+* Add load_filtered method ([#198](https://github.com/J-F-Liu/lopdf/issues/198))
+* Add as_string method to Object ([#196](https://github.com/J-F-Liu/lopdf/issues/196))
+
+### Adding
+
+* Adding Comments to examples ([#220](https://github.com/J-F-Liu/lopdf/issues/220))
+
+### Fix
+
+* Fix clippy warning
+* Fix cliippy warnings
+* Fix datetime using time crate
+* Fix Cargo.toml ([#213](https://github.com/J-F-Liu/lopdf/issues/213))
+* Fix ci build issue ([#209](https://github.com/J-F-Liu/lopdf/issues/209))
+* Fix extract_text to split text at word boundaries.
+* Fix embed_image feature
+
+### Make
+
+* Make some more objects public. ([#199](https://github.com/J-F-Liu/lopdf/issues/199))
+
+### Readd
+
+* Readd accidently deleted pdf files in assets ([#204](https://github.com/J-F-Liu/lopdf/issues/204))
+
+### Release
+
+* Release 0.30
+
+### Remove
+
+* Remove obsolete lifetime
+
+### Replace
+
+* Replace unmaitained encoding crate with encoding_rs ([#222](https://github.com/J-F-Liu/lopdf/issues/222))
+
+### Set
+
+* Set default to nom_parser and rayon ([#208](https://github.com/J-F-Liu/lopdf/issues/208))
+
+### Update
+
+* Update time dependency ([#206](https://github.com/J-F-Liu/lopdf/issues/206))
+* Update nom dependency
+* Update time dependency
+* Update edition and some dependencies.
+
+
+<a name="v0.29.0"></a>
+## [v0.29.0](https://github.com/J-F-Liu/lopdf/compare/v0.27.0...v0.29.0) (2023-04-09)
+
+### Add
+
+* Add function get_page_annotations and include an example ([#184](https://github.com/J-F-Liu/lopdf/issues/184))
+
+### Added
+
+* Added documentation and improved tests ([#178](https://github.com/J-F-Liu/lopdf/issues/178))
+
+### Allow
+
+* Allow mutable access to the document catalog ([#189](https://github.com/J-F-Liu/lopdf/issues/189))
+
+### Extend
+
+* Extend match layout change and Full bookmark example in merge. ([#179](https://github.com/J-F-Liu/lopdf/issues/179))
+
+### Fix
+
+* Fix nom parser
+* Fix clippy warnings
+* Fix add_barcode example
+* Fix Incremental.pdf
+* Fix documentation issues and make README testable ([#171](https://github.com/J-F-Liu/lopdf/issues/171))
+* Fix pdfutil build error
+* Fix `extend` definition confusion bug ([#161](https://github.com/J-F-Liu/lopdf/issues/161))
+
+### Fixed
+
+* Fixed [#175](https://github.com/J-F-Liu/lopdf/issues/175) and some clippy issues. ([#182](https://github.com/J-F-Liu/lopdf/issues/182))
+
+### Guard
+
+* Guard example based on if the "parser" feature is enabled ([#173](https://github.com/J-F-Liu/lopdf/issues/173))
+
+### Made
+
+* made XREF parser accept an optional space character after 'xref' ([#167](https://github.com/J-F-Liu/lopdf/issues/167))
+
+### Make
+
+* Make add_xobject follow references ([#187](https://github.com/J-F-Liu/lopdf/issues/187))
+* Make xref public ,fix line endings and Fix Xref output so Adobe will open them again. ([#181](https://github.com/J-F-Liu/lopdf/issues/181))
+
+### Merge
+
+* Merge branch 'master' of https://github.com/J-F-Liu/lopdf
+
+### Release
+
+* Release 0.29
+* Release 0.28
+
+### Remove
+
+* Remove --no-default-features test
+
+### Remove
+
+* remove unneccessary time 0.1 dependency ([#163](https://github.com/J-F-Liu/lopdf/issues/163))
+
+### Reorder
+
+* Reorder Pages before Renumbering Objects. ([#193](https://github.com/J-F-Liu/lopdf/issues/193))
+
+### Support
+
+* Support Incremental Updates ([#176](https://github.com/J-F-Liu/lopdf/issues/176))
+
+### Switch
+
+* switch to single-precision floating point ([#190](https://github.com/J-F-Liu/lopdf/issues/190))
+
+### Update
+
+* Update itoa dependency to 1.0 ([#162](https://github.com/J-F-Liu/lopdf/issues/162))
+
+
+<a name="v0.27.0"></a>
+## [v0.27.0](https://github.com/J-F-Liu/lopdf/compare/v0.26.0...v0.27.0) (2021-12-16)
+
+### Add
+
+* Add GitHub Actions build matrix ([#127](https://github.com/J-F-Liu/lopdf/issues/127))
+* Add Change Log
+
+### Added
+
+* Added Object::as_float() to convert numerical values to float. ([#124](https://github.com/J-F-Liu/lopdf/issues/124))
+* Added Object::as_bool ([#123](https://github.com/J-F-Liu/lopdf/issues/123))
+
+### Avoid
+
+* Avoid panic when encounters negative stream length
+
+### Bookmarks
+
+* Bookmarks ([#135](https://github.com/J-F-Liu/lopdf/issues/135))
+
+### Change
+
+* Change indent_style to space
+
+### Check
+
+* Check stream length
+
+### Do
+
+* Do not limit Real precision to two digits ([#155](https://github.com/J-F-Liu/lopdf/issues/155))
+
+### Fix
+
+* Fix document save race in parser_aux::load_and_save and creator::create_document ([#151](https://github.com/J-F-Liu/lopdf/issues/151))
+* Fix clippy warnings & add clippy build job ([#128](https://github.com/J-F-Liu/lopdf/issues/128))
+
+### Preserve
+
+* Preserve the eol characters in literal strings ([#131](https://github.com/J-F-Liu/lopdf/issues/131))
+
+### Reduce
+
+* Reduce allocation by reusing the iterator ([#129](https://github.com/J-F-Liu/lopdf/issues/129))
+
+### Release
+
+* Release 0.27
+* Release pdfutil 0.4
+
+### Replace
+
+* Replace lzw with weezl ([#140](https://github.com/J-F-Liu/lopdf/issues/140))
+
+### Return
+
+* Return early on error in `Stream::filters` ([#130](https://github.com/J-F-Liu/lopdf/issues/130))
+
+### Unwrap
+
+* Unwrap the text ([#119](https://github.com/J-F-Liu/lopdf/issues/119))
+
+### Update
+
+* Update nom to 6.0 ([#126](https://github.com/J-F-Liu/lopdf/issues/126))
+
+
+<a name="v0.26.0"></a>
+## [v0.26.0](https://github.com/J-F-Liu/lopdf/compare/v0.25.0...v0.26.0) (2020-09-29)
+
+### Add
+
+* Add as_str, as_str_mut methods to Object ([#107](https://github.com/J-F-Liu/lopdf/issues/107))
+
+### Dtoa
+
+* dtoa may write real number in exponential format which is not allowed in PDF
+
+### Genericize
+
+* Genericize Content to allow AsRef<[Operation]> ([#111](https://github.com/J-F-Liu/lopdf/issues/111))
+
+### Make
+
+* Make pom dependency optional (but default) ([#112](https://github.com/J-F-Liu/lopdf/issues/112))
+* Make rayon dependency optional ([#108](https://github.com/J-F-Liu/lopdf/issues/108))
+
+### Merge
+
+* Merge document PDF logic with some fixes ([#117](https://github.com/J-F-Liu/lopdf/issues/117))
+
+### Various
+
+* Various improvements, updated libraries and image features ([#118](https://github.com/J-F-Liu/lopdf/issues/118))
+
+
+<a name="v0.25.0"></a>
+## [v0.25.0](https://github.com/J-F-Liu/lopdf/compare/v0.24.0...v0.25.0) (2020-06-25)
+
+### Add
+
+* add indexing checks ([#98](https://github.com/J-F-Liu/lopdf/issues/98))
+
+### Add
+
+* Add a test for [#93](https://github.com/J-F-Liu/lopdf/issues/93) ([#95](https://github.com/J-F-Liu/lopdf/issues/95))
+
+### Bugfix
+
+* Bugfix for xref_start. ([#105](https://github.com/J-F-Liu/lopdf/issues/105))
+
+### Check
+
+* check that the buffer is big enough for startxref ([#93](https://github.com/J-F-Liu/lopdf/issues/93))
+
+### Create
+
+* Create rust.yml ([#104](https://github.com/J-F-Liu/lopdf/issues/104))
+
+### Extend
+
+* extend recursion limit to non-local references ([#100](https://github.com/J-F-Liu/lopdf/issues/100))
+
+### Fix
+
+* Fix compilation error&test error ([#102](https://github.com/J-F-Liu/lopdf/issues/102))
+
+### Keep
+
+* keep looking for the last pattern ([#94](https://github.com/J-F-Liu/lopdf/issues/94))
+
+### Limit
+
+* Limit allowed bracket depth. ([#97](https://github.com/J-F-Liu/lopdf/issues/97))
+
+### Limit
+
+* limit recursion to the number of objects ([#92](https://github.com/J-F-Liu/lopdf/issues/92))
+
+### Move
+
+* Move bracket depth checking into parsers. ([#101](https://github.com/J-F-Liu/lopdf/issues/101))
+
+### Release
+
+* Release 0.25
+
+### Return
+
+* Return Result from as_array_mut() ([#106](https://github.com/J-F-Liu/lopdf/issues/106))
+
+### Update
+
+* Update itoa and linked-hash-map ([#91](https://github.com/J-F-Liu/lopdf/issues/91))
+
+
+<a name="v0.24.0"></a>
+## [v0.24.0](https://github.com/J-F-Liu/lopdf/compare/v0.23.0...v0.24.0) (2020-02-17)
+
+### Compute
+
+* Compute an accurate iterator size when the page tree is sane.
+
+### Fix
+
+* Fix datetime parser ([#89](https://github.com/J-F-Liu/lopdf/issues/89))
+
+### More
+
+* More permissive datetime parsing ([#90](https://github.com/J-F-Liu/lopdf/issues/90))
+
+### Release
+
+* Release 0.24
+
+### Validate
+
+* Validate expected id in pom parser.
+* Validate the expected id when reading indirect objects.
+
+
+<a name="v0.23.0"></a>
+## [v0.23.0](https://github.com/J-F-Liu/lopdf/compare/v0.22.0...v0.23.0) (2019-07-14)
+
+### Adapt
+
+* Adapt pom parser.
+
+### Add
+
+* Add error descriptions.
+* Add a proper error type and remove some more panics.
+
+### Allow
+
+* Allow loading a document from a memory slice.
+
+### Avoid
+
+* Avoid allocating an intermediate collection for iteration.
+* Avoid unwraps when already returning an Option for failure.
+
+### Error
+
+* Error signaling around compression and image handling.
+
+### Escape
+
+* Escape fix ([#68](https://github.com/J-F-Liu/lopdf/issues/68))
+
+### Export
+
+* Export dereference function as it is useful for PDF consumers.
+* Export filters module.
+
+### Get_font_encoding
+
+* get_font_encoding seems more at home with Dictionary.
+
+### Handle
+
+* Handle stream filter chains ([#66](https://github.com/J-F-Liu/lopdf/issues/66))
+
+### Hex
+
+* Hex fix ([#67](https://github.com/J-F-Liu/lopdf/issues/67))
+
+### Implement
+
+* Implement LZW decompression.
+
+### Improve
+
+* Improve hex parsing performance.
+
+### Make
+
+* Make a page iterator.
+* Make Reader::read consume the Reader.
+* Make content operations faillible.
+
+### Protect
+
+* Protect against reference loops.
+* Protect against a corrupted page tree.
+
+### Refactor
+
+* Refactor a bit to allow a utility function.
+
+### Release
+
+* Release 0.23.0
+
+### Remove
+
+* Remove intermediate assignation.
+* Remove unsafe code around FilterType.
+* Remove unsafe code on get_object_mut.
+* Remove some 'if let' for readability.
+* Remove more panic paths in xref parsing.
+
+### Replace
+
+* Replace unwraps in processor.rs.
+
+### Return
+
+* Return results when appropriate.
+
+### Separate
+
+* Separate decompression into two functions.
+
+### Take
+
+* Take care of panic that I actually hit on the pom side.
+* Take care of creator.rs.
+
+### Unify
+
+* Unify buffer creation.
+
+### Use
+
+* Use lifetime ellision.
+* Use TryInto.
+* Use writeln where appropriate.
+* Use error enum in reader.
+* Use stable cloned.
+
+
+<a name="v0.22.0"></a>
+## [v0.22.0](https://github.com/J-F-Liu/lopdf/compare/v0.21.0...v0.22.0) (2019-05-13)
+
+### Add
+
+* Add parsing benchmark.
+* Add nom dependency.
+
+### Also
+
+* Also test with nom parsing feature enabled.
+
+### Array
+
+* Array and dictionary parsing.
+
+### Avoid
+
+* Avoid using format! when writing.
+
+### Be
+
+* Be explicit about trait objects.
+
+### Boolean
+
+* Boolean and null parsing.
+
+### Content
+
+* Content parsing.
+
+### Duplicate
+
+* Duplicate pom parser for incremental replacement with nom 5.
+
+### Ease
+
+* Ease off on rayon a bit.
+
+### Escape
+
+* Escape sequence parsing.
+
+### Extern
+
+* extern crate is not required anymore with 2018 edition.
+
+### Fix
+
+* Fix last ugly parser.
+* Fix octal parser.
+* Fix pdfutil build
+
+### Float
+
+* Float parsing.
+
+### Header
+
+* Header parsing.
+
+### Hex
+
+* Hex string parsing.
+
+### Indirect
+
+* Indirect object and stream parsing.
+
+### Literal
+
+* Literal string syntax.
+
+### Make
+
+* Make sure Stream.start_position is relative to the whole file.
+
+### Merge
+
+* Merge remote-tracking branch 'upstream/master' into nom5
+* Merge remote-tracking branch 'upstream/master' into nom5
+
+### More
+
+* More 2018 edition lints.
+* More cleanup.
+* More cleanup.
+* More simplifications.
+
+### Object
+
+* Object id and reference parsing.
+
+### Octal
+
+* Octal and hexadecimal parsing.
+
+### Parallel
+
+* Parallel object stream parsing.
+
+### Rayon
+
+* Rayon usage proof of concept.
+
+### Release
+
+* Release 0.22.0
+
+### Remove
+
+* Remove pom dependency in tests.
+
+### Replace
+
+* Replace name parser.
+
+### Resolve
+
+* Resolve name collisions.
+
+### Simplify
+
+* Simplify lifetime annotations.
+
+### Slowly
+
+* Slowly replace the cute pom parser with nom.
+
+### Trailer
+
+* Trailer and xref start.
+
+### Turns
+
+* Turns out "contained" already exists in nom.
+
+### Unify
+
+* Unify both variants of the parsing functions.
+
+### Use
+
+* Use a BufWriter when saving to path.
+* Use parse_at(&self.buffer, offset) to read indirect_object
+* Use nom digit testing functions.
+* Use lifetime ellision.
+* Use nom sequence operators.
+
+### Useless
+
+* Useless move.
+
+### Xref
+
+* Xref stream and trailer parsing.
+* Xref parsing.
+
+
+<a name="v0.21.0"></a>
+## [v0.21.0](https://github.com/J-F-Liu/lopdf/compare/v0.20.0...v0.21.0) (2019-04-26)
+
+### Avoid
+
+* Avoid allocating a String.
+
+### Check
+
+* Check offsets read from file to avoid panics
+* Check and correct Size entry of trailer dictionary
+
+### Clean
+
+* Clean up bytes_to_string, string_to_bytes iterators
+
+### Fix
+
+* Fix clippy warnings
+* Fix .editorconfig
+
+### Fixed
+
+* fixed finally
+
+### Redundant
+
+* Redundant imports with 2018 edition.
+
+### Release
+
+* Release 0.21.0
+
+### Update
+
+* Update example
+* Update Cargo.toml
+
+### Use
+
+* Use env_logger in pdfutil
+
+
+<a name="v0.20.0"></a>
+## [v0.20.0](https://github.com/J-F-Liu/lopdf/compare/v0.19.0...v0.20.0) (2019-03-07)
+
+### Release
+
+* Release 0.20.0
+
+### Replace
+
+* Replace println with log macros
+
+### Use
+
+* Use Rust 2018
+* Use pom 3.0
+
+
+<a name="v0.19.0"></a>
+## [v0.19.0](https://github.com/J-F-Liu/lopdf/compare/v0.18.0...v0.19.0) (2018-10-24)
+
+### Allow
+
+* Allow xref section has zero entries
+
+### Dictionary
+
+* Dictionary key type changed to Vec<u8>
+
+### Format
+
+* Format code with rustfmt
+
+### Improve
+
+* Improve codestyle (simplify loops, remove closures, use is_empty() etc.)
+
+### Move
+
+* Move image dependency to embed_image feature
+
+### Release
+
+* Release 0.19.0
+
+### Skip
+
+* Skip corrupt deflate stream
+
+
+<a name="v0.18.0"></a>
+## [v0.18.0](https://github.com/J-F-Liu/lopdf/compare/v0.17.0...v0.18.0) (2018-10-05)
+
+### Able
+
+* Able to read stream when it's length is in object stream
+
+### Adress
+
+* Adress timezone formatting problem from [#34](https://github.com/J-F-Liu/lopdf/issues/34)
+
+### Insert
+
+* insert image on page
+
+
+<a name="v0.17.0"></a>
+## [v0.17.0](https://github.com/J-F-Liu/lopdf/compare/v0.16.0...v0.17.0) (2018-09-19)
+
+### Make
+
+* Make chrono crate optional
+
+### Release
+
+* Release 0.17.0
+
+### Update
+
+* Update add_barcode example
+
+
+<a name="v0.16.0"></a>
+## [v0.16.0](https://github.com/J-F-Liu/lopdf/compare/v0.15.3...v0.16.0) (2018-09-18)
+
+### Add
+
+* Add form xobject to page
+* Add extract_stream subcommand
+
+### Compress
+
+* Compress created Form xobject
+
+### Compress
+
+* compress page content after change
+
+### Fix
+
+* Fix collect_fonts_from_resources for referenced resources
+* Fix add xobject to page resources as direct object
+
+
+<a name="v0.15.3"></a>
+## [v0.15.3](https://github.com/J-F-Liu/lopdf/compare/v0.15.0...v0.15.3) (2018-09-14)
+
+### Decompress
+
+* Decompress Form XObject
+
+### Disable
+
+* Disable auto format markdown
+
+### Fix
+
+* Fix bug in reading incremental updated document
+* Fix build warning
+* Fix string_to_bytes method
+
+### Hexadecimal
+
+* Hexadecimal strings can contain white space.
+
+### Remove
+
+* Remove println in extract_text
+
+### Update
+
+* Update example code
+* Update example
+
+
+<a name="v0.15.0"></a>
+## [v0.15.0](https://github.com/J-F-Liu/lopdf/compare/v0.14.1...v0.15.0) (2018-02-04)
+
+### Add
+
+* add `get_object_mut`
+* add method as_array_mut
+
+### Extract
+
+* Extract text from specified pages
+
+### Replace
+
+* Replace text of specified page
+
+
+<a name="v0.14.1"></a>
+## [v0.14.1](https://github.com/J-F-Liu/lopdf/compare/v0.13.0...v0.14.1) (2017-11-03)
+
+### Add
+
+* Add `impl From<_> for Object` for more numeric types
+* Add an Object::string_literal constructor
+* Add a `dictionary!` macro that creates a Dictionary
+* Add `impl From<ObjectId> for Object` creating Object::Reference
+
+### Derive
+
+* Derive Clone for lopdf::Document
+
+### Release
+
+* Release 0.14.0
+
+### Remove
+
+* Remove the Seek bound on Document::save_to
+
+
+<a name="v0.13.0"></a>
+## [v0.13.0](https://github.com/J-F-Liu/lopdf/compare/v0.11.0...v0.13.0) (2017-10-02)
+
+### Avoid
+
+* Avoid decompress flate stream which has Subtype
+
+### Debug
+
+* Debug with lldb
+
+### Fix
+
+* Fix get_object for created document
+
+### Ignore
+
+* Ignore invalid objects when reading all object in xref table
+
+### Impl
+
+* impl fmt::Debug for Object
+
+### Pdfutil
+
+* pdfutil add extract_pages command
+
+### Read
+
+* Read optional space at the end of xref subsection header line
+
+### Release
+
+* Release 0.13.0
+* Release 0.12.0
+
+### Store
+
+* Store compressed stream objects and normal objects together
+
+
+<a name="v0.11.0"></a>
+## [v0.11.0](https://github.com/J-F-Liu/lopdf/compare/v0.10.0...v0.11.0) (2017-08-21)
+
+### Release
+
+* Release 0.11.0
+
+### Use
+
+* Use itoa and dtoa to improve writing performance
+
+
+<a name="v0.10.0"></a>
+## [v0.10.0](https://github.com/J-F-Liu/lopdf/compare/v0.9.0...v0.10.0) (2017-07-20)
+
+### Added
+
+* Added optional allows_compression for Stream object
+
+### Release
+
+* Release 0.10.0
+
+
+<a name="v0.9.0"></a>
+## [v0.9.0](https://github.com/J-F-Liu/lopdf/compare/v0.8.0...v0.9.0) (2017-05-24)
+
+### Add
+
+* Add pdfutil readme
+
+### Added
+
+* Added unit test for load_from() and save_to()
+* Added Document::with_version + refactored save() and load()
+* Added Debug trait for lopdf::Document
+
+### Apply
+
+* Apply multiple operations in one command
+
+### Build
+
+* Build with Rust stable
+* Build with Rust beta
+
+### Fix
+
+* Fix delete_zero_length_streams
+
+### Fixed
+
+* Fixed unit tests
+* Fixed breaking API changes
+
+### Release
+
+* Release 0.9.0
+
+
+<a name="v0.8.0"></a>
+## [v0.8.0](https://github.com/J-F-Liu/lopdf/compare/v0.7.0...v0.8.0) (2017-03-16)
+
+### Change
+
+* Change Name(String) to Name(Vec<u8>)
+
+### Delete_object
+
+* delete_object and delete_unused_objects
+
+### Get_pages
+
+* get_pages and delete_pages
+
+### Handle
+
+* Handle zero length stream
+
+### Release
+
+* Release 0.8.0
+
+### Traverse
+
+* Traverse objects from trailer recursively
+
+
+<a name="v0.7.0"></a>
+## [v0.7.0](https://github.com/J-F-Liu/lopdf/compare/v0.6.0...v0.7.0) (2017-03-07)
+
+### Add
+
+* Add Content::decode() function
+
+### Build
+
+* Build on Rust 1.17
+
+### Create
+
+* Create String object for DateTime
+
+### Parse
+
+* Parse PDF datetime value
+
+### Read
+
+* Read xref stream in hybrid-reference file
+
+### Update
+
+* Update create_document example
+* Update README
+
+
+<a name="v0.6.0"></a>
+## [v0.6.0](https://github.com/J-F-Liu/lopdf/compare/v0.5.0...v0.6.0) (2017-02-16)
+
+### Add
+
+* Add Stream::decompressed_content() method
+
+### Read
+
+* Read previous Xrefs of linearized or incremental updated document
+
+
+<a name="v0.5.0"></a>
+## [v0.5.0](https://github.com/J-F-Liu/lopdf/compare/v0.4.0...v0.5.0) (2017-02-10)
+
+### Add
+
+* Add size field to Xref
+* Add Xref struct
+
+### Decode
+
+* Decode PNG frame after FlateDecode
+
+### Read
+
+* Read compressed objects from object stream
+* Read xref stream
+
+### Update
+
+* Update README
+
+### Use
+
+* Use pom 0.9.0
+
+### XrefEntry
+
+* XrefEntry as enum type
+
+
+<a name="v0.4.0"></a>
+## [v0.4.0](https://github.com/J-F-Liu/lopdf/compare/v0.3.0...v0.4.0) (2017-01-29)
+
+### Add
+
+* Add Operation constructor
+* Add modify_text test
+* Add travis-ci build status
+* Add FAQ in Readme
+* Add print_xref_size() for debuging
+
+### Decode
+
+* Decode content stream
+
+### Encode
+
+* Encode content operations
+
+### Fix
+
+* Fix load_document test
+* Fix https://github.com/rust-lang/rust/issues/39177
+
+### Optimize
+
+* Optimize parser code
+
+### Solve
+
+* Solve mutual reference problem between Pages and Page objects
+
+### Trigger
+
+* Trigger new release to pass build on docs.rs
+
+### Update
+
+* Update create PDF example
+
+
+<a name="v0.3.0"></a>
+## [v0.3.0](https://github.com/J-F-Liu/lopdf/compare/v0.2.0...v0.3.0) (2017-01-18)
+
+### Add
+
+* Add compress/decompress subcommands to pdfutil
+
+### Create
+
+* create PDF parser using pom instead of nom
+
+### Dictionary
+
+* Dictionary preserve key insert order
+
+### Update
+
+* Update README
+* Update parser to use pom 0.6.0
+
+### Use
+
+* Use reader to get stream length if it is a reference object
+
+
+<a name="v0.2.0"></a>
+## [v0.2.0](https://github.com/J-F-Liu/lopdf/compare/v0.1.0...v0.2.0) (2017-01-05)
+
+### Add
+
+* Add pdfutil program
+
+### Fix
+
+* Fix parsing PDF array error
+
+### Improve
+
+* Improve documentation
+
+
+<a name="v0.1.0"></a>
+## v0.1.0 (2016-12-23)
+
+### Editor
+
+* Editor config
+
+### Impl
+
+* impl Document add_object method
+
+### Improve
+
+* Improve Document::save functional type
+
+### Initial
+
+* Initial commit
+
+### PDF
+
+* PDF objects and document definition
+
+### Parse
+
+* Parse and load PDF document
+
+### Read
+
+* Read objects from xref table instead of sequentially from file stream
+
+### Save
+
+* Save PDF document to file
+
+### Store
+
+* Store max_id as a field of document
+
diff --git a/vendor/lopdf/Cargo.toml b/vendor/lopdf/Cargo.toml
new file mode 100644
index 000000000..5b324210e
--- /dev/null
+++ b/vendor/lopdf/Cargo.toml
@@ -0,0 +1,465 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+rust-version = "1.88"
+name = "lopdf"
+version = "0.45.0"
+authors = [
+ "Junfeng Liu <[email protected]>",
+ "Emulator <[email protected]>",
+]
+build = false
+exclude = [
+ "/benches",
+ "/assets",
+ "/.chglog",
+ "/.vscode",
+ "/.github",
+]
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "A Rust library for PDF document manipulation."
+homepage = "https://github.com/J-F-Liu/lopdf"
+documentation = "https://docs.rs/crate/lopdf/"
+readme = "README.md"
+keywords = [
+ "pdf",
+ "editing",
+ "manipulation",
+ "merge",
+]
+categories = ["text-processing"]
+license = "MIT"
+repository = "https://github.com/J-F-Liu/lopdf.git"
+
+[badges.travis-ci]
+repository = "J-F-Liu/lopdf"
+
+[features]
+async = [
+ "tokio/rt-multi-thread",
+ "tokio/macros",
+]
+chrono = ["dep:chrono"]
+chrono-clock = [
+ "chrono",
+ "chrono/clock",
+]
+default = [
+ "chrono-clock",
+ "rayon",
+]
+embed_image = ["image"]
+font_embedding = ["dep:skrifa"]
+jiff = ["dep:jiff"]
+serde = ["dep:serde"]
+time = ["dep:time"]
+wasm_js = ["getrandom/wasm_js"]
+
+[lib]
+name = "lopdf"
+path = "src/lib.rs"
+
+[[example]]
+name = "add_barcode"
+path = "examples/add_barcode.rs"
+
+[[example]]
+name = "analyze_object_streams"
+path = "examples/analyze_object_streams.rs"
+
+[[example]]
+name = "analyze_page_contents"
+path = "examples/analyze_page_contents.rs"
+
+[[example]]
+name = "analyze_pdf"
+path = "examples/analyze_pdf.rs"
+
+[[example]]
+name = "analyze_references"
+path = "examples/analyze_references.rs"
+
+[[example]]
+name = "check_raw_objstream"
+path = "examples/check_raw_objstream.rs"
+
+[[example]]
+name = "compress_existing_pdf"
+path = "examples/compress_existing_pdf.rs"
+
+[[example]]
+name = "create"
+path = "examples/create.rs"
+
+[[example]]
+name = "create_text_heavy_pdf"
+path = "examples/create_text_heavy_pdf.rs"
+
+[[example]]
+name = "debug_compression_detailed"
+path = "examples/debug_compression_detailed.rs"
+
+[[example]]
+name = "debug_compression_full"
+path = "examples/debug_compression_full.rs"
+
+[[example]]
+name = "debug_object_stream"
+path = "examples/debug_object_stream.rs"
+
+[[example]]
+name = "debug_save_with_objstreams"
+path = "examples/debug_save_with_objstreams.rs"
+
+[[example]]
+name = "decompression_bomb"
+path = "examples/decompression_bomb.rs"
+
+[[example]]
+name = "decrypt"
+path = "examples/decrypt.rs"
+
+[[example]]
+name = "delete_outlines"
+path = "examples/delete_outlines.rs"
+
+[[example]]
+name = "encrypt"
+path = "examples/encrypt.rs"
+
+[[example]]
+name = "extract_text"
+path = "examples/extract_text.rs"
+required-features = ["serde"]
+
+[[example]]
+name = "extract_toc"
+path = "examples/extract_toc.rs"
+required-features = ["serde"]
+
+[[example]]
+name = "final_compression_test"
+path = "examples/final_compression_test.rs"
+
+[[example]]
+name = "inspect_object_stream"
+path = "examples/inspect_object_stream.rs"
+
+[[example]]
+name = "merge"
+path = "examples/merge.rs"
+
+[[example]]
+name = "object_streams"
+path = "examples/object_streams.rs"
+
+[[example]]
+name = "print_annotations"
+path = "examples/print_annotations.rs"
+
+[[example]]
+name = "replace_partial_text"
+path = "examples/replace_partial_text.rs"
+
+[[example]]
+name = "rotate"
+path = "examples/rotate.rs"
+
+[[example]]
+name = "test_better_compression"
+path = "examples/test_better_compression.rs"
+
+[[example]]
+name = "test_decryption"
+path = "examples/test_decryption.rs"
+
+[[example]]
+name = "test_direct_objstream"
+path = "examples/test_direct_objstream.rs"
+
+[[example]]
+name = "test_filter_roundtrip"
+path = "examples/test_filter_roundtrip.rs"
+
+[[example]]
+name = "test_metadata"
+path = "examples/test_metadata.rs"
+
+[[example]]
+name = "test_object_stream_creation"
+path = "examples/test_object_stream_creation.rs"
+
+[[example]]
+name = "test_object_stream_roundtrip"
+path = "examples/test_object_stream_roundtrip.rs"
+
+[[example]]
+name = "test_real_pdf_compression_with_fix"
+path = "examples/test_real_pdf_compression_with_fix.rs"
+
+[[example]]
+name = "test_structural_compression"
+path = "examples/test_structural_compression.rs"
+
+[[example]]
+name = "verify_decryption"
+path = "examples/verify_decryption.rs"
+
+[[example]]
+name = "verify_page_compression"
+path = "examples/verify_page_compression.rs"
+
+[[example]]
+name = "verify_pdf"
+path = "examples/verify_pdf.rs"
+
+[[example]]
+name = "verify_trailer_compression_fix"
+path = "examples/verify_trailer_compression_fix.rs"
+
+[[test]]
+name = "annotation"
+path = "tests/annotation.rs"
+
+[[test]]
+name = "brotli_decode"
+path = "tests/brotli_decode.rs"
+
+[[test]]
+name = "catalog_compression_integration_test"
+path = "tests/catalog_compression_integration_test.rs"
+
+[[test]]
+name = "decompression_bomb"
+path = "tests/decompression_bomb.rs"
+
+[[test]]
+name = "decryption"
+path = "tests/decryption.rs"
+
+[[test]]
+name = "document_load_performance"
+path = "tests/document_load_performance.rs"
+
+[[test]]
+name = "encrypted_object_stream_test"
+path = "tests/encrypted_object_stream_test.rs"
+
+[[test]]
+name = "extract_test"
+path = "tests/extract_test.rs"
+
+[[test]]
+name = "font_test"
+path = "tests/font_test.rs"
+
+[[test]]
+name = "incremental_document"
+path = "tests/incremental_document.rs"
+
+[[test]]
+name = "linearized_objstm_test"
+path = "tests/linearized_objstm_test.rs"
+
+[[test]]
+name = "load_options_test"
+path = "tests/load_options_test.rs"
+
+[[test]]
+name = "metadata_test"
+path = "tests/metadata_test.rs"
+
+[[test]]
+name = "modify"
+path = "tests/modify.rs"
+
+[[test]]
+name = "object_stream_comprehensive_test"
+path = "tests/object_stream_comprehensive_test.rs"
+
+[[test]]
+name = "object_stream_edge_cases_test"
+path = "tests/object_stream_edge_cases_test.rs"
+
+[[test]]
+name = "object_stream_methods_test"
+path = "tests/object_stream_methods_test.rs"
+
+[[test]]
+name = "object_stream_performance_test"
+path = "tests/object_stream_performance_test.rs"
+
+[[test]]
+name = "page_content"
+path = "tests/page_content.rs"
+
+[[test]]
+name = "save_options_xref_streams_test"
+path = "tests/save_options_xref_streams_test.rs"
+
+[[test]]
+name = "simple_object_stream_test"
+path = "tests/simple_object_stream_test.rs"
+
+[[test]]
+name = "stream_length_recovery"
+path = "tests/stream_length_recovery.rs"
+
+[[test]]
+name = "trailer_reference_compression_test"
+path = "tests/trailer_reference_compression_test.rs"
+
+[[test]]
+name = "unicode"
+path = "tests/unicode.rs"
+
+[[test]]
+name = "utils"
+path = "tests/utils.rs"
+
+[[test]]
+name = "xref_reconstruction"
+path = "tests/xref_reconstruction.rs"
+
+[[test]]
+name = "xref_stream_bounds"
+path = "tests/xref_stream_bounds.rs"
+
+[dependencies.aes]
+version = "0.9"
+
+[dependencies.bitflags]
+version = "2.13"
+
+[dependencies.brotli-decompressor]
+version = "5.0"
+
+[dependencies.cbc]
+version = "0.2"
+
+[dependencies.chrono]
+version = "0.4"
+features = ["std"]
+optional = true
+default-features = false
+
+[dependencies.ecb]
+version = "0.2"
+
+[dependencies.encoding_rs]
+version = "0.8"
+
+[dependencies.flate2]
+version = "1.1"
+
+[dependencies.getrandom]
+version = "0.4"
+
+[dependencies.image]
+version = "0.25"
+optional = true
+
+[dependencies.indexmap]
+version = "2.14"
+
+[dependencies.itoa]
+version = "1.0"
+
+[dependencies.jiff]
+version = "0.2"
+optional = true
+
+[dependencies.log]
+version = "0.4"
+
+[dependencies.md-5]
+version = "0.11"
+
+[dependencies.nom]
+version = "8.0"
+
+[dependencies.rand]
+version = "0.10"
+
+[dependencies.rangemap]
+version = "1.7"
+
+[dependencies.rayon]
+version = "1.12"
+optional = true
+
+[dependencies.serde]
+version = "1.0"
+features = ["derive"]
+optional = true
+
+[dependencies.sha2]
+version = "0.11"
+
+[dependencies.skrifa]
+version = "0.45.1"
+optional = true
+
+[dependencies.stringprep]
+version = "0.1.5"
+
+[dependencies.thiserror]
+version = "2.0"
+
+[dependencies.time]
+version = "0.3"
+features = [
+ "formatting",
+ "parsing",
+]
+optional = true
+
+[dependencies.tokio]
+version = "1"
+features = [
+ "fs",
+ "io-util",
+]
+optional = true
+
+[dependencies.weezl]
+version = "0.2"
+
+[dev-dependencies.clap]
+version = "4.6"
+features = ["derive"]
+
+[dev-dependencies.env_logger]
+version = "0.11"
+
+[dev-dependencies.flate2]
+version = "1.1"
+
+[dev-dependencies.serde_json]
+version = "1.0"
+
+[dev-dependencies.shellexpand]
+version = "3.1"
+
+[dev-dependencies.tempfile]
+version = "3.27"
+
+[dev-dependencies.wasm-bindgen-test]
+version = "0.3"
+
+[target.'cfg(not(target_family="wasm"))'.dev-dependencies.criterion]
+version = "0.8"
diff --git a/vendor/lopdf/Cargo.toml.orig b/vendor/lopdf/Cargo.toml.orig
new file mode 100644
index 000000000..da97acf08
--- /dev/null
+++ b/vendor/lopdf/Cargo.toml.orig
@@ -0,0 +1,107 @@
+[package]
+authors = [
+ "Junfeng Liu <[email protected]>",
+ "Emulator <[email protected]>",
+]
+categories = ["text-processing"]
+description = "A Rust library for PDF document manipulation."
+documentation = "https://docs.rs/crate/lopdf/"
+edition = "2024"
+homepage = "https://github.com/J-F-Liu/lopdf"
+keywords = ["pdf", "editing", "manipulation", "merge"]
+license = "MIT"
+name = "lopdf"
+readme = "README.md"
+repository = "https://github.com/J-F-Liu/lopdf.git"
+version = "0.45.0"
+rust-version = "1.88"
+exclude = ["/benches", "/assets", "/.chglog", "/.vscode", "/.github"]
+
+[dependencies]
+aes = "0.9"
+bitflags = "2.13"
+brotli-decompressor = "5.0"
+cbc = "0.2"
+chrono = { version = "0.4", optional = true, default-features = false, features = [
+ "std",
+] }
+ecb = "0.2"
+encoding_rs = "0.8"
+flate2 = "1.1"
+image = { version = "0.25", optional = true }
+indexmap = "2.14"
+itoa = "1.0"
+jiff = { version = "0.2", optional = true }
+getrandom = "0.4"
+log = "0.4"
+md-5 = "0.11"
+nom = "8.0"
+rand = { version = "0.10" }
+rangemap = "1.7"
+rayon = { version = "1.12", optional = true }
+serde = { version = "1.0", features = ["derive"], optional = true }
+sha2 = "0.11"
+stringprep = "0.1.5"
+thiserror = "2.0"
+time = { version = "0.3", features = [
+ "formatting",
+ "parsing",
+], optional = true }
+tokio = { version = "1", features = ["fs", "io-util"], optional = true }
+weezl = "0.2"
+skrifa = { version = "0.45.1", optional = true }
+
+[dev-dependencies]
+clap = { version = "4.6", features = ["derive"] }
+env_logger = "0.11"
+flate2 = "1.1"
+serde_json = "1.0"
+shellexpand = "3.1"
+tempfile = "3.27"
+wasm-bindgen-test = "0.3"
+
+[target.'cfg(not(target_family="wasm"))'.dev-dependencies]
+criterion = "0.8"
+
+[features]
+async = ["tokio/rt-multi-thread", "tokio/macros"]
+# Fixed-offset and UTC conversions, which is all a PDF date can express.
+chrono = ["dep:chrono"]
+# The system-local conversions, and the iana-time-zone subtree they need.
+chrono-clock = ["chrono", "chrono/clock"]
+default = ["chrono-clock", "rayon"]
+embed_image = ["image"]
+font_embedding = ["dep:skrifa"]
+jiff = ["dep:jiff"]
+wasm_js = ["getrandom/wasm_js"]
+serde = ["dep:serde"]
+time = ["dep:time"]
+
+[[example]]
+name = "extract_toc"
+required-features = ["serde"]
+
+[[example]]
+name = "extract_text"
+required-features = ["serde"]
+
+[[example]]
+name = "print_annotations"
+# No `required-features`: the example uses `env_logger` (a dev-dependency,
+# always available to an example) and `Document`/`Object`, none of which is
+# behind a feature. Naming `default` only made it silently unbuildable under
+# `--no-default-features`.
+
+[[example]]
+name = "rotate"
+
+[[bench]]
+name = "datetime"
+harness = false
+
+[[bench]]
+name = "parse"
+harness = false
+
+[badges]
+travis-ci = { repository = "J-F-Liu/lopdf" }
diff --git a/vendor/lopdf/LICENSE b/vendor/lopdf/LICENSE
new file mode 100644
index 000000000..c15fe13e2
--- /dev/null
+++ b/vendor/lopdf/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2016 Junfeng Liu
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/lopdf/README.md b/vendor/lopdf/README.md
new file mode 100644
index 000000000..bc754f211
--- /dev/null
+++ b/vendor/lopdf/README.md
@@ -0,0 +1,862 @@
+# lopdf
+
+[![Crates.io](https://img.shields.io/crates/v/lopdf.svg)](https://crates.io/crates/lopdf)
+[![CI](https://github.com/J-F-Liu/lopdf/actions/workflows/ci.yml/badge.svg)](https://github.com/J-F-Liu/lopdf/actions/workflows/ci.yml)
+[![Docs]( https://docs.rs/lopdf/badge.svg)](https://docs.rs/lopdf)
+
+A Rust library for PDF document manipulation.
+
+A useful reference for understanding the PDF file format and the
+eventual usage of this library is the
+[PDF 1.7 Reference Document](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf).
+The PDF 2.0 specification is available [here](https://www.pdfa.org/announcing-no-cost-access-to-iso-32000-2-pdf-2-0/).
+
+## Requirements
+
+- **Rust 1.85 or later** - Required for Rust 2024 edition features and object streams support
+- To check your Rust version: `rustc --version`
+- To update Rust: `rustup update`
+
+## Cargo features
+
+| Feature | Default | What it adds |
+| --- | :---: | --- |
+| `chrono-clock` | ✅ | `chrono` plus its `clock` feature: conversions to and from `DateTime<Local>`, the reading machine's own zone. Brings `iana-time-zone` and its per-platform chain. |
+| `rayon` | ✅ | Parallel object-stream and cross-reference parsing. |
+| `chrono` | | Conversions to and from `DateTime<FixedOffset>` and `DateTime<Utc>`, which is all a PDF date can express. Costs `chrono` and `num-traits`, nothing else. |
+| `jiff` | | Conversions to and from `jiff::Zoned` and `jiff::Timestamp`. Resolves named zones, so it needs a timezone database — bundled into the binary on Windows and on any wasm target. |
+| `time` | | Conversions to and from `time::OffsetDateTime` and `time::PrimitiveDateTime`. |
+| `serde` | | `Serialize`/`Deserialize` for the object model. |
+| `async` | | Tokio-based asynchronous document loading. |
+| `embed_image` | | Embedding raster images, via the `image` crate. |
+| `font_embedding` | | Embedding TrueType fonts, via `skrifa`. |
+| `wasm_js` | | Selects `getrandom`'s `wasm_js` backend, needed for encryption on wasm. |
+
+The date backends are alternatives, not layers: each supplies conversions for the same [`DateTime`] value, so enabling more than one only adds dependencies. Enabling none is supported too — `Object::as_datetime` needs no backend, and `DateTime::as_str` returns the raw date for a caller that would rather parse it itself.
+
+A PDF date states a fixed offset from UT and never a named zone (ISO 32000-1, 7.9.4), so `chrono` without `clock` is enough to read one faithfully. `chrono-clock` is the default only because it is what earlier versions gave you.
+
+## Example Code
+
+* Create PDF document
+
+```rust
+use lopdf::dictionary;
+use lopdf::{Document, Object, Stream};
+use lopdf::content::{Content, Operation};
+
+// `with_version` specifes the PDF version this document complies with.
+let mut doc = Document::with_version("1.5");
+// Object IDs are used for cross referencing in PDF documents.
+// `lopdf` helps keep track of them for us. They are simple integers.
+// Calls to `doc.new_object_id` and `doc.add_object` return an object ID.
+
+// "Pages" is the root node of the page tree.
+let pages_id = doc.new_object_id();
+
+// Fonts are dictionaries. The "Type", "Subtype" and "BaseFont" tags
+// are straight out of the PDF spec.
+//
+// The dictionary macro is a helper that allows complex
+// key-value relationships to be represented in a simpler
+// visual manner, similar to a match statement.
+// A dictionary is implemented as an IndexMap of Vec<u8>, and Object
+let font_id = doc.add_object(dictionary! {
+ // type of dictionary
+ "Type" => "Font",
+ // type of font, type1 is simple postscript font
+ "Subtype" => "Type1",
+ // basefont is postscript name of font for type1 font.
+ // See PDF reference document for more details
+ "BaseFont" => "Courier",
+});
+
+// Font dictionaries need to be added into resource
+// dictionaries in order to be used.
+// Resource dictionaries can contain more than just fonts,
+// but normally just contains fonts.
+// Only one resource dictionary is allowed per page tree root.
+let resources_id = doc.add_object(dictionary! {
+ // Fonts are actually triplely nested dictionaries. Fun!
+ "Font" => dictionary! {
+ // F1 is the font name used when writing text.
+ // It must be unique in the document. It does not
+ // have to be F1
+ "F1" => font_id,
+ },
+});
+
+// `Content` is a wrapper struct around an operations struct that contains
+// a vector of operations. The operations struct contains a vector of
+// that match up with a particular PDF operator and operands.
+// Refer to the PDF spec for more details on the operators and operands
+// Note, the operators and operands are specified in a reverse order
+// from how they actually appear in the PDF file itself.
+let content = Content {
+ operations: vec![
+ // BT begins a text element. It takes no operands.
+ Operation::new("BT", vec![]),
+ // Tf specifies the font and font size.
+ // Font scaling is complicated in PDFs.
+ // Refer to the spec for more info.
+ // The `into()` methods convert the types into
+ // an enum that represents the basic object types in PDF documents.
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ // Td adjusts the translation components of the text matrix.
+ // When used for the first time after BT, it sets the initial
+ // text position on the page.
+ // Note: PDF documents have Y=0 at the bottom. Thus 600 to print text near the top.
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ // Tj prints a string literal to the page. By default, this is black text that is
+ // filled in. There are other operators that can produce various textual effects and
+ // colors
+ Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
+ // ET ends the text element.
+ Operation::new("ET", vec![]),
+ ],
+};
+
+// Streams are a dictionary followed by a (possibly encoded) sequence of bytes.
+// What that sequence of bytes represents, depends on the context.
+// The stream dictionary is set internally by lopdf and normally doesn't
+// need to be manually manipulated. It contains keys such as
+// Length, Filter, DecodeParams, etc.
+let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+
+// Page is a dictionary that represents one page of a PDF file.
+// Its required fields are "Type", "Parent" and "Contents".
+let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+});
+
+// Again, "Pages" is the root of the page tree. The ID was already created
+// at the top of the page, since we needed it to assign to the parent element
+// of the page dictionary.
+//
+// These are just the basic requirements for a page tree root object.
+// There are also many additional entries that can be added to the dictionary,
+// if needed. Some of these can also be defined on the page dictionary itself,
+// and not inherited from the page tree root.
+let pages = dictionary! {
+ // Type of dictionary
+ "Type" => "Pages",
+ // Vector of page IDs in document. Normally would contain more than one ID
+ // and be produced using a loop of some kind.
+ "Kids" => vec![page_id.into()],
+ // Page count
+ "Count" => 1,
+ // ID of resources dictionary, defined earlier
+ "Resources" => resources_id,
+ // A rectangle that defines the boundaries of the physical or digital media.
+ // This is the "page size".
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+};
+
+// Using `insert()` here, instead of `add_object()` since the ID is already known.
+doc.objects.insert(pages_id, Object::Dictionary(pages));
+
+// Creating document catalog.
+// There are many more entries allowed in the catalog dictionary.
+let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+});
+
+// The "Root" key in trailer is set to the ID of the document catalog,
+// the remainder of the trailer is set during `doc.save()`.
+doc.trailer.set("Root", catalog_id);
+doc.compress();
+
+// Store file in current working directory.
+// Note: Line is excluded when running tests
+if false {
+ // Traditional save
+ doc.save("example.pdf").unwrap();
+
+ // Or save with object streams for smaller file size
+ let mut file = std::fs::File::create("example_compressed.pdf").unwrap();
+ doc.save_modern(&mut file).unwrap();
+}
+```
+
+* Merge PDF documents
+
+```rust
+use lopdf::dictionary;
+
+use std::collections::BTreeMap;
+
+use lopdf::content::{Content, Operation};
+use lopdf::{Document, Object, ObjectId, Stream, Bookmark};
+
+pub fn generate_fake_document() -> Document {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Courier",
+ });
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
+ Operation::new("ET", vec![]),
+ ],
+ };
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ });
+ let pages = dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ doc
+}
+
+fn main() -> std::io::Result<()> {
+ // Generate a stack of Documents to merge.
+ let documents = vec![
+ generate_fake_document(),
+ generate_fake_document(),
+ generate_fake_document(),
+ generate_fake_document(),
+ ];
+
+ // Define a starting `max_id` (will be used as start index for object_ids).
+ let mut max_id = 1;
+ let mut pagenum = 1;
+ // Collect all Documents Objects grouped by a map
+ let mut documents_pages = BTreeMap::new();
+ let mut documents_objects = BTreeMap::new();
+ let mut document = Document::with_version("1.5");
+
+ for mut doc in documents {
+ let mut first = false;
+ doc.renumber_objects_with(max_id);
+
+ max_id = doc.max_id + 1;
+
+ documents_pages.extend(
+ doc
+ .get_pages()
+ .into_iter()
+ .map(|(_, object_id)| {
+ if !first {
+ let bookmark = Bookmark::new(String::from(format!("Page_{}", pagenum)), [0.0, 0.0, 1.0], 0, object_id);
+ document.add_bookmark(bookmark, None);
+ first = true;
+ pagenum += 1;
+ }
+
+ (
+ object_id,
+ doc.get_object(object_id).unwrap().to_owned(),
+ )
+ })
+ .collect::<BTreeMap<ObjectId, Object>>(),
+ );
+ documents_objects.extend(doc.objects);
+ }
+
+ // "Catalog" and "Pages" are mandatory.
+ let mut catalog_object: Option<(ObjectId, Object)> = None;
+ let mut pages_object: Option<(ObjectId, Object)> = None;
+
+ // Process all objects except "Page" type
+ for (object_id, object) in documents_objects.iter() {
+ // We have to ignore "Page" (as are processed later), "Outlines" and "Outline" objects.
+ // All other objects should be collected and inserted into the main Document.
+ match object.type_name().unwrap_or(b"") {
+ b"Catalog" => {
+ // Collect a first "Catalog" object and use it for the future "Pages".
+ catalog_object = Some((
+ if let Some((id, _)) = catalog_object {
+ id
+ } else {
+ *object_id
+ },
+ object.clone(),
+ ));
+ }
+ b"Pages" => {
+ // Collect and update a first "Pages" object and use it for the future "Catalog"
+ // We have also to merge all dictionaries of the old and the new "Pages" object
+ if let Ok(dictionary) = object.as_dict() {
+ let mut dictionary = dictionary.clone();
+ if let Some((_, ref object)) = pages_object {
+ if let Ok(old_dictionary) = object.as_dict() {
+ dictionary.extend(old_dictionary);
+ }
+ }
+
+ pages_object = Some((
+ if let Some((id, _)) = pages_object {
+ id
+ } else {
+ *object_id
+ },
+ Object::Dictionary(dictionary),
+ ));
+ }
+ }
+ b"Page" => {} // Ignored, processed later and separately
+ b"Outlines" => {} // Ignored, not supported yet
+ b"Outline" => {} // Ignored, not supported yet
+ _ => {
+ document.objects.insert(*object_id, object.clone());
+ }
+ }
+ }
+
+ // If no "Pages" object found, abort.
+ if pages_object.is_none() {
+ println!("Pages root not found.");
+
+ return Ok(());
+ }
+
+ // Iterate over all "Page" objects and collect into the parent "Pages" created before
+ for (object_id, object) in documents_pages.iter() {
+ if let Ok(dictionary) = object.as_dict() {
+ let mut dictionary = dictionary.clone();
+ dictionary.set("Parent", pages_object.as_ref().unwrap().0);
+
+ document
+ .objects
+ .insert(*object_id, Object::Dictionary(dictionary));
+ }
+ }
+
+ // If no "Catalog" found, abort.
+ if catalog_object.is_none() {
+ println!("Catalog root not found.");
+
+ return Ok(());
+ }
+
+ let catalog_object = catalog_object.unwrap();
+ let pages_object = pages_object.unwrap();
+
+ // Build a new "Pages" with updated fields
+ if let Ok(dictionary) = pages_object.1.as_dict() {
+ let mut dictionary = dictionary.clone();
+
+ // Set new pages count
+ dictionary.set("Count", documents_pages.len() as u32);
+
+ // Set new "Kids" list (collected from documents pages) for "Pages"
+ dictionary.set(
+ "Kids",
+ documents_pages
+ .into_iter()
+ .map(|(object_id, _)| Object::Reference(object_id))
+ .collect::<Vec<_>>(),
+ );
+
+ document
+ .objects
+ .insert(pages_object.0, Object::Dictionary(dictionary));
+ }
+
+ // Build a new "Catalog" with updated fields
+ if let Ok(dictionary) = catalog_object.1.as_dict() {
+ let mut dictionary = dictionary.clone();
+ dictionary.set("Pages", pages_object.0);
+ dictionary.remove(b"Outlines"); // Outlines not supported in merged PDFs
+
+ document
+ .objects
+ .insert(catalog_object.0, Object::Dictionary(dictionary));
+ }
+
+ document.trailer.set("Root", catalog_object.0);
+
+ // Update the max internal ID as wasn't updated before due to direct objects insertion
+ document.max_id = document.objects.len() as u32;
+
+ // Reorder all new Document objects
+ document.renumber_objects();
+
+ // Set any Bookmarks to the First child if they are not set to a page
+ document.adjust_zero_pages();
+
+ // Set all bookmarks to the PDF Object tree then set the Outlines to the Bookmark content map.
+ if let Some(n) = document.build_outline() {
+ if let Ok(Object::Dictionary(dict)) = document.get_object_mut(catalog_object.0) {
+ dict.set("Outlines", Object::Reference(n));
+ }
+ }
+
+ document.compress();
+
+ // Save the merged PDF.
+ // Store file in current working directory.
+ // Note: Line is excluded when running doc tests
+ if false {
+ document.save("merged.pdf").unwrap();
+ }
+
+ Ok(())
+}
+```
+
+* Decrypt PDF documents
+
+```rust
+use lopdf::Document;
+
+// Load and decrypt PDF documents with empty password
+#[cfg(not(feature = "async"))]
+{
+ // Load an encrypted PDF - automatically attempts decryption with empty password
+ let doc = Document::load("assets/encrypted.pdf").unwrap();
+
+ // Check if the document is encrypted
+ if doc.is_encrypted() {
+ println!("Document is encrypted");
+
+ // The document has been automatically decrypted if the password was empty
+ if doc.encryption_state.is_some() {
+ println!("Successfully decrypted with empty password");
+ }
+ }
+
+ // Access decrypted content
+ let pages = doc.get_pages();
+ println!("Number of pages: {}", pages.len());
+
+ // Extract text from decrypted document
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = doc.extract_text(&page_numbers).unwrap();
+ println!("Extracted {} characters of text", text.len());
+
+ // Access individual objects
+ for i in 1..=10 {
+ if let Ok(obj) = doc.get_object((i, 0)) {
+ println!("Successfully accessed object ({}, 0)", i);
+ }
+ }
+}
+
+#[cfg(feature = "async")]
+{
+ tokio::runtime::Builder::new_current_thread()
+ .build()
+ .expect("Failed to create runtime")
+ .block_on(async move {
+ // Async version
+ let doc = Document::load("assets/encrypted.pdf").await.unwrap();
+
+ if doc.is_encrypted() {
+ println!("Document is encrypted");
+ if doc.encryption_state.is_some() {
+ println!("Successfully decrypted with empty password");
+ }
+ }
+
+ let pages = doc.get_pages();
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = doc.extract_text(&page_numbers).unwrap();
+ println!("Extracted {} characters of text", text.len());
+ });
+}
+```
+
+* Modify PDF document
+
+```rust
+use lopdf::Document;
+
+// For this example to work a parser feature needs to be enabled
+#[cfg(not(feature = "async"))]
+#[cfg(feature = "nom_parser")]
+{
+ let mut doc = Document::load("assets/example.pdf").unwrap();
+
+ doc.version = "1.4".to_string();
+ doc.replace_text(1, "Hello World!", "Modified text!", None);
+ // Store file in current working directory.
+ // Note: Line is excluded when running tests
+ if false {
+ doc.save("modified.pdf").unwrap();
+ }
+}
+
+#[cfg(feature = "async")]
+#[cfg(feature = "nom_parser")]
+{
+ tokio::runtime::Builder::new_current_thread()
+ .build()
+ .expect("Failed to create runtime")
+ .block_on(async move {
+ let mut doc = Document::load("assets/example.pdf").await.unwrap();
+
+ doc.version = "1.4".to_string();
+ doc.replace_text(1, "Hello World!", "Modified text!", None);
+ // Store file in current working directory.
+ // Note: Line is excluded when running tests
+ if false {
+ doc.save("modified.pdf").unwrap();
+ }
+ });
+}
+
+// For this example to work a parser feature needs to be enabled
+#[cfg(not(feature = "async"))]
+#[cfg(feature = "nom_parser")]
+{
+ let mut doc = Document::load("assets/example.pdf").unwrap();
+
+ doc.version = "1.4".to_string();
+
+ // Replace exact text matches
+ doc.replace_text(1, "Hello World!", "Modified text!", None);
+
+ // Replace partial text matches (new method)
+ let count = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
+ println!("Replaced {} occurrences", count);
+
+ // Store file in current working directory.
+ // Note: Line is excluded when running tests
+ if false {
+ doc.save("modified.pdf").unwrap();
+ }
+}
+
+#[cfg(feature = "async")]
+#[cfg(feature = "nom_parser")]
+{
+ tokio::runtime::Builder::new_current_thread()
+ .build()
+ .expect("Failed to create runtime")
+ .block_on(async move {
+ let mut doc = Document::load("assets/example.pdf").await.unwrap();
+
+ doc.version = "1.4".to_string();
+
+ // Replace exact text matches
+ doc.replace_text(1, "Hello World!", "Modified text!", None);
+
+ // Replace partial text matches (new method)
+ let count = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
+ println!("Replaced {} occurrences", count);
+
+ // Store file in current working directory.
+ // Note: Line is excluded when running tests
+ if false {
+ doc.save("modified.pdf").unwrap();
+ }
+ });
+}
+```
+
+* Save PDF with Object Streams (Modern Format)
+
+Object streams allow multiple non-stream objects to be compressed together, significantly reducing file size.
+
+```rust,no_run
+use lopdf::{Document, SaveOptions};
+
+#[cfg(not(feature = "async"))]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Load existing PDF
+ let mut doc = Document::load("input.pdf")?;
+
+ // Save with modern features (object streams + cross-reference streams)
+ // This typically reduces file size by 11-38%
+ let mut file = std::fs::File::create("output.pdf")?;
+ doc.save_modern(&mut file)?;
+
+ // For more control, use SaveOptions
+ let options = SaveOptions::builder()
+ .use_object_streams(true) // Enable object streams
+ .use_xref_streams(true) // Enable cross-reference streams
+ .max_objects_per_stream(200) // Max objects per stream (default: 100)
+ .compression_level(9) // Compression level 0-9 (default: 6)
+ .build();
+
+ let mut file2 = std::fs::File::create("output_custom.pdf")?;
+ doc.save_with_options(&mut file2, options)?;
+
+ Ok(())
+}
+
+#[cfg(feature = "async")]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // For async feature, you need to use tokio runtime
+ println!("This example requires the async feature to be disabled");
+ Ok(())
+}
+```
+
+### Complete Example: Creating and Saving with Object Streams
+
+```rust
+use lopdf::{Document, SaveOptions};
+use std::fs::File;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Create or load a document
+ let mut doc = Document::with_version("1.5");
+ // ... add content to document ...
+
+ // Method 1: Quick modern save (recommended)
+ let mut file = File::create("output.pdf")?;
+ doc.save_modern(&mut file)?;
+
+ // Method 2: Custom settings for maximum compression
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .max_objects_per_stream(200)
+ .compression_level(9)
+ .build();
+
+ let mut file2 = File::create("output_max_compressed.pdf")?;
+ doc.save_with_options(&mut file2, options)?;
+
+ // Compare file sizes (if traditional file exists)
+ if std::path::Path::new("output_traditional.pdf").exists() {
+ let traditional_size = std::fs::metadata("output_traditional.pdf")?.len();
+ let modern_size = std::fs::metadata("output.pdf")?.len();
+ let reduction = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
+ println!("Size reduction: {:.1}%", reduction);
+ }
+
+ Ok(())
+}
+```
+
+For more examples, see:
+- [`examples/object_streams.rs`](examples/object_streams.rs) - Creating PDFs with object streams
+- [`examples/compress_existing_pdf.rs`](examples/compress_existing_pdf.rs) - Compress existing PDFs
+- [`examples/analyze_object_streams.rs`](examples/analyze_object_streams.rs) - Analyze object stream usage
+
+## Object Streams Support
+
+lopdf now includes full support for creating and reading PDF object streams (PDF 1.5+ feature). Object streams provide significant file size reduction by compressing multiple non-stream objects together.
+
+### Key Benefits
+
+- **File size reduction**: 11-61% smaller PDFs depending on content
+- **Modern PDF compliance**: Full PDF 1.5+ specification support
+- **Backward compatibility**: All existing APIs remain unchanged
+- **Performance**: <2ms to check 1000 objects for compression eligibility
+
+### Creating Object Streams Directly
+
+```rust
+use lopdf::{Object, ObjectStream, dictionary};
+
+# fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Create an object stream with custom settings
+ let mut obj_stream = ObjectStream::builder()
+ .max_objects(100) // Maximum objects per stream
+ .compression_level(6) // zlib compression level (0-9)
+ .build();
+
+ // Add objects to the stream
+ obj_stream.add_object((1, 0), Object::Integer(42))?;
+ obj_stream.add_object((2, 0), Object::Name(b"Example".to_vec()))?;
+ obj_stream.add_object((3, 0), Object::Dictionary(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ }))?;
+
+ // Convert to a stream object
+ let stream = obj_stream.to_stream_object()?;
+ # Ok::<(), Box<dyn std::error::Error>>(())
+# }
+```
+
+### Object Eligibility
+
+Not all objects can be compressed into object streams. The following objects are **excluded**:
+
+- Stream objects (content streams, image streams, etc.)
+- Cross-reference streams (Type = XRef)
+- Object streams themselves (Type = ObjStm)
+- Encryption dictionary (when referenced by trailer's Encrypt entry)
+- Objects with generation number > 0
+- Document catalog in linearized PDFs only
+
+All other objects, including structural objects (Catalog, Pages, Page) and trailer-referenced objects (except encryption), can be compressed.
+
+### Cross-reference Streams
+
+When using `save_modern()` or enabling `use_xref_streams(true)`, lopdf creates binary cross-reference streams instead of traditional ASCII cross-reference tables. This provides additional space savings and is part of the PDF 1.5+ specification.
+
+### SaveOptions Reference
+
+The `SaveOptions` builder provides fine-grained control over PDF compression:
+
+```rust
+use lopdf::SaveOptions;
+
+let options = SaveOptions::builder()
+ .use_object_streams(true) // Enable object streams (default: false)
+ .use_xref_streams(true) // Enable xref streams (default: false)
+ .max_objects_per_stream(200) // Max objects per stream (default: 100)
+ .compression_level(9) // zlib level 0-9 (default: 6)
+ .build();
+```
+
+## PDF Decryption Support
+
+lopdf now includes enhanced support for reading encrypted PDF documents. The library can automatically decrypt PDFs that use empty passwords, which is common for many protected documents.
+
+### Key Features
+
+- **Automatic decryption**: PDFs encrypted with empty passwords are automatically decrypted on load
+- **Object stream support**: Handles encrypted PDFs containing compressed object streams
+- **Transparent access**: Once decrypted, all document methods work normally
+- **Preservation of structure**: Document structure and content remain intact after decryption
+
+### How It Works
+
+When loading an encrypted PDF, lopdf:
+1. Detects encryption via the `Encrypt` entry in the trailer
+2. Extracts raw object bytes before parsing
+3. Attempts authentication with an empty password
+4. Decrypts all objects if authentication succeeds
+5. Processes compressed objects from object streams
+
+### Example: Working with Encrypted PDFs
+
+```rust
+use lopdf::Document;
+
+#[cfg(not(feature = "async"))]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Load an encrypted PDF - automatically attempts decryption
+ let doc = Document::load("assets/encrypted.pdf")?;
+
+ // Check encryption status
+ if doc.is_encrypted() {
+ println!("Document is encrypted");
+
+ // Check if decryption was successful
+ if doc.encryption_state.is_some() {
+ println!("Successfully decrypted");
+
+ // Now you can work with the document normally
+ let pages = doc.get_pages();
+ println!("Pages: {}", pages.len());
+
+ // Extract text
+ let page_nums: Vec<u32> = pages.keys().cloned().collect();
+ let text = doc.extract_text(&page_nums)?;
+ println!("Text length: {} chars", text.len());
+
+ // Access objects
+ for i in 1..=10 {
+ if let Ok(_) = doc.get_object((i, 0)) {
+ println!("Object ({}, 0) accessible", i);
+ }
+ }
+ } else {
+ println!("Decryption failed - password required");
+ }
+ }
+
+ Ok(())
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Load an encrypted PDF - automatically attempts decryption
+ let doc = Document::load("assets/encrypted.pdf").await?;
+
+ // Check encryption status
+ if doc.is_encrypted() {
+ println!("Document is encrypted");
+
+ // Check if decryption was successful
+ if doc.encryption_state.is_some() {
+ println!("Successfully decrypted");
+
+ // Now you can work with the document normally
+ let pages = doc.get_pages();
+ println!("Pages: {}", pages.len());
+
+ // Extract text
+ let page_nums: Vec<u32> = pages.keys().cloned().collect();
+ let text = doc.extract_text(&page_nums)?;
+ println!("Text length: {} chars", text.len());
+
+ // Access objects
+ for i in 1..=10 {
+ if let Ok(_) = doc.get_object((i, 0)) {
+ println!("Object ({}, 0) accessible", i);
+ }
+ }
+ } else {
+ println!("Decryption failed - password required");
+ }
+ }
+
+ Ok(())
+}
+```
+
+### Limitations
+
+- Currently only supports PDFs encrypted with empty passwords
+- Password-protected PDFs require manual authentication (use `authenticate_password` method)
+- Some encryption algorithms may not be fully supported
+
+For more examples, see:
+- [`examples/test_decryption.rs`](examples/test_decryption.rs) - Testing decryption functionality
+- [`examples/verify_decryption.rs`](examples/verify_decryption.rs) - Comprehensive decryption verification
+- [`tests/decryption.rs`](tests/decryption.rs) - Decryption test suite
+
+## FAQ
+
+* Why does the library keep everything in memory as high-level objects until finally serializing the entire document?
+
+ Normally, a PDF document won't be very large, ranging from tens of KB to hundreds of MB. Memory size is not a bottle neck for today's computer.
+ By keeping the whole document in memory, the stream length can be pre-calculated, no need to use a reference object for the Length entry.
+ The resulting PDF file is smaller for distribution and faster for PDF consumers to process.
+
+ Producing is a one-time effort, while consuming is many more.
+
+* How do object streams affect memory usage?
+
+ Object streams actually help reduce memory usage during document creation. When enabled, multiple small objects are grouped and compressed together, reducing the overall memory footprint. The compression happens during the save operation, so the in-memory representation remains the same until `save_with_options()` or `save_modern()` is called.
+
+* What PDF versions support object streams?
+
+ Object streams were introduced in PDF 1.5. When using `save_modern()` or object streams, lopdf automatically ensures the document version is at least 1.5. For maximum compatibility with older PDF readers, you can use the traditional `save()` method.
+
+* Can I analyze existing PDFs to see if they use object streams?
+
+ Yes! lopdf can read and parse object streams from existing PDFs. Use the `Document::load()` method to open any PDF, and lopdf will automatically handle object streams if present. See the examples directory for analysis tools.
+
+## License
+
+lopdf is available under the MIT license, with the exception of the Montserrat font.
\ No newline at end of file
diff --git a/vendor/lopdf/examples/add_barcode.rs b/vendor/lopdf/examples/add_barcode.rs
new file mode 100644
index 000000000..87908a41a
--- /dev/null
+++ b/vendor/lopdf/examples/add_barcode.rs
@@ -0,0 +1,105 @@
+use lopdf::Document;
+use lopdf::xobject;
+use std::fmt::Write;
+use std::io::Error;
+use std::path::Path;
+use std::str::FromStr;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+fn convert_number_to_bits<T: std::fmt::Binary>(num: T, size: usize) -> Vec<u8> {
+ let bin = format!("{:b}", num);
+ let pad = "0".repeat(size - bin.len());
+ let mut bytes = (pad + &bin).into_bytes();
+ bytes.reverse();
+ bytes
+}
+
+fn generate_barcode(page: u32, code: u16) -> Vec<(f64, f64, f64, f64, u8)> {
+ assert!(page > 0 && page <= 255, "Page number should within range: 1-255");
+ assert!(code <= 511, "Bar code should within range: 0-511");
+ let page_bits = convert_number_to_bits(page, 8);
+ let code_bits = convert_number_to_bits(code, 9);
+ let mut rects = vec![];
+ let mut x = 0.0;
+ let y = 0.0;
+ let w = 9.0;
+ let h = 10.0;
+ {
+ let mut add_flag = |w, bit| {
+ rects.push((x, y, w, h, bit));
+ x += w;
+ };
+ add_flag(w, b'0');
+ for bit in page_bits {
+ add_flag(w, bit);
+ }
+ add_flag(w, code_bits[0]);
+ add_flag(6.53, b'0');
+ add_flag(w, code_bits[1]);
+ add_flag(w, code_bits[2]);
+ add_flag(w, code_bits[3]);
+ add_flag(w, code_bits[4]);
+ add_flag(w, b'1');
+ add_flag(w, b'0');
+ add_flag(w, code_bits[5]);
+ add_flag(w, code_bits[6]);
+ add_flag(w, code_bits[7]);
+ add_flag(w, code_bits[8]);
+ }
+ rects
+}
+
+fn generate_operations(rects: Vec<(f64, f64, f64, f64, u8)>) -> String {
+ let mut operations = String::new();
+ let mut current_color = b'\0';
+ for (x, y, w, h, bit) in rects {
+ if bit != current_color {
+ operations.push_str(match bit {
+ b'0' => "1 1 1 rg\n",
+ b'1' => "0 0 0 rg\n",
+ _ => "\n",
+ });
+ current_color = bit;
+ }
+ write!(&mut operations, "{} {} {} {} re\nf\n", x, y, w, h).unwrap();
+ }
+ operations
+}
+
+#[cfg(not(feature = "async"))]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Document::load(path).map_err(|e| Error::other(e.to_string()))
+}
+
+#[cfg(feature = "async")]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Builder::new_current_thread()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await.map_err(|e| Error::other(e.to_string())) })
+}
+
+#[allow(non_upper_case_globals)]
+const mm2pt: f32 = 2.834;
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ assert!(args.len() == 4, "Not enough arguments: pdf_file bar_code output_file");
+ let pdf_file = &args[1];
+ let code = u16::from_str(&args[2]).expect("error in parsing code argument");
+ let output_file = &args[3];
+ let mut doc = load_pdf(pdf_file).unwrap();
+ for (page_number, page_id) in doc.get_pages() {
+ let operations = generate_operations(generate_barcode(page_number, code));
+ let barcode = xobject::form(
+ vec![0.0, 0.0, 595.0 - 12.44 * mm2pt * 2.0, 10.0 * mm2pt],
+ vec![mm2pt, 0.0, 0.0, mm2pt, 12.44 * mm2pt, 842.0 - 14.53 * mm2pt],
+ operations.as_bytes().to_vec(),
+ );
+ doc.insert_form_object(page_id, barcode).unwrap();
+ }
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
diff --git a/vendor/lopdf/examples/analyze_object_streams.rs b/vendor/lopdf/examples/analyze_object_streams.rs
new file mode 100644
index 000000000..5aba1b252
--- /dev/null
+++ b/vendor/lopdf/examples/analyze_object_streams.rs
@@ -0,0 +1,211 @@
+use lopdf::{Document, Object};
+use std::collections::HashMap;
+use std::env;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+fn main() {
+ let args: Vec<String> = env::args().collect();
+ if args.len() < 2 {
+ eprintln!("Usage: {} <pdf_file>", args[0]);
+ std::process::exit(1);
+ }
+
+ let pdf_path = &args[1];
+ println!("Analyzing PDF: {}", pdf_path);
+ println!("{}", "=".repeat(80));
+
+ match load_document(pdf_path) {
+ Ok(doc) => {
+ analyze_document(&doc);
+ }
+ Err(e) => {
+ eprintln!("Failed to load PDF: {}", e);
+ std::process::exit(1);
+ }
+ }
+}
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn analyze_document(doc: &Document) {
+ println!("PDF Version: {:?}", doc.version);
+ println!("Total objects: {}", doc.objects.len());
+
+ // Find object streams
+ let mut object_streams = Vec::new();
+ let mut compressed_objects = HashMap::new();
+
+ for (id, obj) in &doc.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ object_streams.push(id);
+
+ // Get info about this object stream
+ if let Ok(n) = stream.dict.get(b"N")
+ && let Ok(count) = n.as_i64()
+ {
+ println!("\nObject Stream {} 0 R:", id.0);
+ println!(" Contains {} objects", count);
+
+ if let Ok(first) = stream.dict.get(b"First")
+ && let Ok(first_offset) = first.as_i64()
+ {
+ println!(" First object at offset: {}", first_offset);
+ }
+
+ // Try to parse the stream content
+ match stream.decompressed_content() {
+ Ok(decompressed) => {
+ println!(" Decompressed size: {} bytes", decompressed.len());
+
+ // Parse the offset table
+ if let Ok(first_offset) = stream.dict.get(b"First").and_then(|o| o.as_i64()) {
+ if first_offset as usize <= decompressed.len() {
+ let offset_table = &decompressed[..first_offset as usize];
+ if let Ok(offset_str) = std::str::from_utf8(offset_table) {
+ let numbers: Vec<_> = offset_str.split_whitespace().collect();
+ println!(" Objects in stream:");
+ for chunk in numbers.chunks(2) {
+ if chunk.len() == 2 {
+ println!(" - Object {}: offset {}", chunk[0], chunk[1]);
+ if let Ok(obj_num) = chunk[0].parse::<u32>() {
+ compressed_objects.insert(obj_num, id.0);
+ }
+ }
+ }
+ } else {
+ println!(" ERROR: Could not parse offset table as UTF-8");
+ println!(" First 100 bytes: {:?}", &offset_table[..offset_table.len().min(100)]);
+ }
+ } else {
+ println!(
+ " ERROR: First offset {} exceeds decompressed size {}",
+ first_offset,
+ decompressed.len()
+ );
+ }
+ }
+ }
+ Err(e) => {
+ println!(" ERROR: Could not decompress stream: {}", e);
+ println!(" Stream is compressed: {}", stream.allows_compression);
+ if let Ok(filter) = stream.dict.get(b"Filter") {
+ println!(" Filter: {:?}", filter);
+ } else {
+ println!(" No Filter found in dictionary!");
+ println!(" Dictionary: {:?}", stream.dict);
+ }
+ println!(" Raw content size: {} bytes", stream.content.len());
+ println!(
+ " First 20 bytes of raw content: {:?}",
+ &stream.content[..stream.content.len().min(20)]
+ );
+ }
+ }
+ }
+ }
+ }
+
+ println!("\nTotal object streams: {}", object_streams.len());
+ println!("Total compressed objects: {}", compressed_objects.len());
+
+ // Check pages
+ println!("\n{}", "=".repeat(80));
+ println!("Page Analysis:");
+
+ let pages = doc.get_pages();
+ println!("Total pages: {}", pages.len());
+
+ for (page_num, &page_id) in pages.iter() {
+ println!("\nPage {}:", page_num);
+ match doc.get_object(page_id) {
+ Ok(page_obj) => {
+ if let Object::Dictionary(page_dict) = page_obj {
+ // Check if page is in object stream
+ if compressed_objects.contains_key(&page_id.0) {
+ println!(
+ " ⚠️ Page object is compressed in object stream {}!",
+ compressed_objects[&page_id.0]
+ );
+ }
+
+ // Check page contents
+ if let Ok(contents) = page_dict.get(b"Contents") {
+ match contents {
+ Object::Reference(ref_id) => {
+ println!(" Contents: {} {} R", ref_id.0, ref_id.1);
+ if compressed_objects.contains_key(&ref_id.0) {
+ println!(
+ " ⚠️ Contents is compressed in object stream {}!",
+ compressed_objects[&ref_id.0]
+ );
+ }
+ }
+ Object::Array(refs) => {
+ println!(" Contents array with {} elements", refs.len());
+ for (i, content_ref) in refs.iter().enumerate() {
+ if let Object::Reference(ref_id) = content_ref
+ && compressed_objects.contains_key(&ref_id.0)
+ {
+ println!(" ⚠️ Content[{}] {} {} R is compressed!", i, ref_id.0, ref_id.1);
+ }
+ }
+ }
+ _ => println!(" Unexpected Contents type: {:?}", contents),
+ }
+ }
+
+ // Check resources
+ if let Ok(resources) = page_dict.get(b"Resources")
+ && let Object::Reference(ref_id) = resources
+ && compressed_objects.contains_key(&ref_id.0)
+ {
+ println!(" ⚠️ Resources {} {} R is compressed!", ref_id.0, ref_id.1);
+ }
+ }
+ }
+ Err(e) => {
+ println!(" Error getting page object: {}", e);
+ if compressed_objects.contains_key(&page_id.0) {
+ println!(" Note: Page is in object stream {}", compressed_objects[&page_id.0]);
+ }
+ }
+ }
+ }
+
+ // Check cross-reference
+ println!("\n{}", "=".repeat(80));
+ println!("Cross-reference Analysis:");
+ println!("Cross-reference type: {:?}", doc.reference_table.cross_reference_type);
+
+ // Check if any critical objects are compressed
+ println!("\n{}", "=".repeat(80));
+ println!("Critical Objects Check:");
+
+ if let Ok(root) = doc.trailer.get(b"Root")
+ && let Object::Reference(root_id) = root
+ {
+ if compressed_objects.contains_key(&root_id.0) {
+ println!("⚠️ WARNING: Catalog (Root) object {} is compressed!", root_id.0);
+ } else {
+ println!("✓ Catalog (Root) object {} is not compressed", root_id.0);
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/analyze_page_contents.rs b/vendor/lopdf/examples/analyze_page_contents.rs
new file mode 100644
index 000000000..c88e3a932
--- /dev/null
+++ b/vendor/lopdf/examples/analyze_page_contents.rs
@@ -0,0 +1,173 @@
+use lopdf::{Document, Object};
+use std::env;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn main() {
+ let args: Vec<String> = env::args().collect();
+ if args.len() < 2 {
+ eprintln!("Usage: {} <pdf_file>", args[0]);
+ std::process::exit(1);
+ }
+
+ let pdf_path = &args[1];
+ println!("Analyzing page contents in: {}", pdf_path);
+ println!("{}", "=".repeat(80));
+
+ match load_document(pdf_path) {
+ Ok(doc) => {
+ analyze_pages(&doc);
+ }
+ Err(e) => {
+ eprintln!("Failed to load PDF: {}", e);
+ std::process::exit(1);
+ }
+ }
+}
+
+fn analyze_pages(doc: &Document) {
+ let pages = doc.get_pages();
+ println!("Total pages: {}", pages.len());
+
+ // Check if we have object streams
+ let mut obj_streams = Vec::new();
+ for (id, obj) in &doc.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ obj_streams.push(id.0);
+ }
+ }
+
+ if !obj_streams.is_empty() {
+ println!("\nObject streams found: {:?}", obj_streams);
+ }
+
+ println!("\nAnalyzing pages:");
+ for (page_num, &page_id) in pages.iter() {
+ println!("\n{}", "-".repeat(60));
+ println!("Page {}: Object {} 0 R", page_num, page_id.0);
+
+ match doc.get_object(page_id) {
+ Ok(Object::Dictionary(page_dict)) => {
+ // Check page type
+ if let Ok(type_obj) = page_dict.get(b"Type") {
+ println!(" Type: {:?}", type_obj);
+ }
+
+ // Check Contents
+ match page_dict.get(b"Contents") {
+ Ok(Object::Reference(content_id)) => {
+ println!(" Contents: {} {} R", content_id.0, content_id.1);
+ check_content_stream(doc, *content_id);
+ }
+ Ok(Object::Array(contents)) => {
+ println!(" Contents array with {} elements:", contents.len());
+ for (i, content_ref) in contents.iter().enumerate() {
+ if let Object::Reference(content_id) = content_ref {
+ println!(" [{}] {} {} R", i, content_id.0, content_id.1);
+ check_content_stream(doc, *content_id);
+ }
+ }
+ }
+ Ok(other) => {
+ println!(" Contents: Unexpected type: {:?}", other);
+ }
+ Err(e) => {
+ println!(" Contents: ERROR - {}", e);
+ }
+ }
+
+ // Check Resources
+ match page_dict.get(b"Resources") {
+ Ok(Object::Reference(res_id)) => {
+ println!(" Resources: {} {} R", res_id.0, res_id.1);
+ check_object_location(doc, *res_id);
+ }
+ Ok(Object::Dictionary(_)) => {
+ println!(" Resources: Inline dictionary");
+ }
+ Ok(other) => {
+ println!(" Resources: Unexpected type: {:?}", other);
+ }
+ Err(e) => {
+ println!(" Resources: ERROR - {}", e);
+ }
+ }
+ }
+ Ok(other) => {
+ println!(" ERROR: Page is not a dictionary! Type: {:?}", other);
+ }
+ Err(e) => {
+ println!(" ERROR: Cannot get page object: {}", e);
+ check_object_location(doc, page_id);
+ }
+ }
+ }
+}
+
+fn check_content_stream(doc: &Document, content_id: (u32, u16)) {
+ match doc.get_object(content_id) {
+ Ok(Object::Stream(stream)) => {
+ println!(" ✓ Stream exists");
+ println!(" Length: {}", stream.content.len());
+ if let Ok(filter) = stream.dict.get(b"Filter") {
+ println!(" Filter: {:?}", filter);
+ }
+
+ // Try to get decompressed content
+ match stream.decompressed_content() {
+ Ok(content) => {
+ let preview = String::from_utf8_lossy(&content[..content.len().min(100)]);
+ println!(" Preview: {:?}", preview);
+ }
+ Err(e) => {
+ println!(" ERROR decompressing: {}", e);
+ }
+ }
+ }
+ Ok(other) => {
+ println!(" ERROR: Content is not a stream! Type: {:?}", other);
+ }
+ Err(e) => {
+ println!(" ERROR: Cannot get content stream: {}", e);
+ check_object_location(doc, content_id);
+ }
+ }
+}
+
+fn check_object_location(doc: &Document, obj_id: (u32, u16)) {
+ // Check if object exists
+ if doc.objects.contains_key(&obj_id) {
+ println!(" Note: Object exists in document");
+ } else {
+ println!(
+ " WARNING: Object {} {} R not found in document!",
+ obj_id.0, obj_id.1
+ );
+
+ // Check xref
+ if let Some(xref_entry) = doc.reference_table.get(obj_id.0) {
+ println!(" Xref entry: {:?}", xref_entry);
+ } else {
+ println!(" No xref entry found!");
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/analyze_pdf.rs b/vendor/lopdf/examples/analyze_pdf.rs
new file mode 100644
index 000000000..832bad3e0
--- /dev/null
+++ b/vendor/lopdf/examples/analyze_pdf.rs
@@ -0,0 +1,102 @@
+use lopdf::{Document, Object};
+use std::collections::HashMap;
+use std::env;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let args: Vec<String> = env::args().collect();
+ let input_file = if args.len() > 1 { &args[1] } else { "assets/example.pdf" };
+
+ println!("Analyzing PDF: {}", input_file);
+ let doc = load_document(input_file)?;
+
+ // Count object types
+ let mut type_counts: HashMap<String, usize> = HashMap::new();
+ let mut stream_count = 0;
+ let mut compressible_count = 0;
+
+ for ((_id, _gen), obj) in &doc.objects {
+ let type_name = match obj {
+ Object::Null => "Null",
+ Object::Boolean(_) => "Boolean",
+ Object::Integer(_) => "Integer",
+ Object::Real(_) => "Real",
+ Object::Name(_) => "Name",
+ Object::String(_, _) => "String",
+ Object::Array(_) => "Array",
+ Object::Dictionary(dict) => {
+ // Try to get the Type entry to be more specific
+ if let Ok(Object::Name(name)) = dict.get(b"Type") {
+ let type_str = String::from_utf8_lossy(name);
+ &format!("Dict/{}", type_str)
+ } else {
+ "Dictionary"
+ }
+ }
+ Object::Stream(_) => {
+ stream_count += 1;
+ "Stream"
+ }
+ Object::Reference(_) => "Reference",
+ };
+
+ // Check if object can be compressed
+ if !matches!(obj, Object::Stream(_)) {
+ compressible_count += 1;
+ }
+
+ *type_counts.entry(type_name.to_string()).or_insert(0) += 1;
+ }
+
+ println!("\nPDF Statistics:");
+ println!("Version: {}", doc.version);
+ println!("Total objects: {}", doc.objects.len());
+ println!("Stream objects: {} (cannot be compressed)", stream_count);
+ println!("Compressible objects: {}", compressible_count);
+ println!(
+ "Compression potential: {:.1}%",
+ (compressible_count as f64 / doc.objects.len() as f64) * 100.0
+ );
+
+ println!("\nObject type breakdown:");
+ let mut sorted_types: Vec<_> = type_counts.iter().collect();
+ sorted_types.sort_by_key(|(_, count)| *count);
+ sorted_types.reverse();
+
+ for (type_name, count) in sorted_types {
+ println!(" {}: {}", type_name, count);
+ }
+
+ // Check if already using object streams
+ let has_objstm = doc.objects.values().any(|obj| {
+ if let Object::Dictionary(dict) = obj
+ && let Ok(Object::Name(name)) = dict.get(b"Type")
+ {
+ return name == b"ObjStm";
+ }
+ false
+ });
+
+ println!(
+ "\nAlready using object streams: {}",
+ if has_objstm { "Yes" } else { "No" }
+ );
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/analyze_references.rs b/vendor/lopdf/examples/analyze_references.rs
new file mode 100644
index 000000000..adc567dd0
--- /dev/null
+++ b/vendor/lopdf/examples/analyze_references.rs
@@ -0,0 +1,178 @@
+use lopdf::{Document, Object, ObjectId};
+use std::collections::{HashMap, HashSet};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let pdf_path = "/Users/nicolasdao/Downloads/pdfs/RFQ - SDS WebApp.docx.pdf";
+ println!("Analyzing references in: {}", pdf_path);
+
+ let doc = load_document(pdf_path)?;
+
+ // Build reference graph
+ let mut references: HashMap<ObjectId, HashSet<ObjectId>> = HashMap::new();
+ let mut referenced_by: HashMap<ObjectId, HashSet<ObjectId>> = HashMap::new();
+
+ // Collect all references
+ for (&id, obj) in &doc.objects {
+ let refs = collect_references_from_object(obj);
+ references.insert(id, refs.clone());
+
+ // Build reverse mapping
+ for ref_id in refs {
+ referenced_by.entry(ref_id).or_default().insert(id);
+ }
+ }
+
+ // Also check trailer references
+ let trailer_refs = collect_references_from_dict(&doc.trailer);
+ for ref_id in &trailer_refs {
+ referenced_by.entry(*ref_id).or_default().insert((0, 0));
+ }
+
+ // Analyze specific problematic objects
+ println!("\nAnalyzing problematic objects:");
+
+ // Object 427 (referenced by catalog 431)
+ if let Some(refs_to_427) = referenced_by.get(&(427, 0)) {
+ println!("\nObject 427 0 R is referenced by:");
+ for &ref_id in refs_to_427 {
+ println!(" {} {} R", ref_id.0, ref_id.1);
+ }
+ }
+
+ // Check what object 427 is
+ if let Ok(obj_427) = doc.get_object((427, 0)) {
+ println!("Object 427 is: {:?}", describe_object(obj_427));
+ }
+
+ // Check fonts that reference orphaned objects
+ println!("\nChecking font references:");
+ for &font_id in &[(8, 0), (9, 0), (10, 0), (11, 0), (12, 0)] {
+ if let Ok(Object::Dictionary(font_dict)) = doc.get_object(font_id) {
+ println!("\nFont {} {} R:", font_id.0, font_id.1);
+ for (key, value) in font_dict.iter() {
+ if let Object::Reference(ref_id) = value {
+ let exists = doc.objects.contains_key(ref_id);
+ println!(
+ " {} -> {} {} R (exists: {})",
+ String::from_utf8_lossy(key),
+ ref_id.0,
+ ref_id.1,
+ exists
+ );
+ }
+ }
+ }
+ }
+
+ // Analyze which objects would be compressed
+ println!("\n\nAnalyzing compression eligibility:");
+ let mut would_compress = Vec::new();
+ let mut would_not_compress = Vec::new();
+
+ for (&id, obj) in &doc.objects {
+ if lopdf::ObjectStream::can_be_compressed(id, obj, &doc) {
+ would_compress.push(id);
+ } else {
+ would_not_compress.push(id);
+ }
+ }
+
+ // Check if any compressed objects are referenced by non-compressed objects
+ println!("\nChecking for problematic compressions:");
+ let mut problems = Vec::new();
+
+ for &compressed_id in &would_compress {
+ if let Some(referencers) = referenced_by.get(&compressed_id) {
+ for &referencer_id in referencers {
+ if referencer_id == (0, 0) {
+ // Referenced from trailer
+ problems.push((compressed_id, referencer_id, "trailer"));
+ } else if would_not_compress.contains(&referencer_id) {
+ // Referenced by a non-compressed object
+ problems.push((compressed_id, referencer_id, "non-compressed object"));
+ }
+ }
+ }
+ }
+
+ if !problems.is_empty() {
+ println!("\nFOUND {} PROBLEMATIC COMPRESSIONS:", problems.len());
+ for (compressed_id, referencer_id, reason) in problems.iter().take(20) {
+ println!(
+ " {} {} R would be compressed but is referenced by {} {} R ({})",
+ compressed_id.0, compressed_id.1, referencer_id.0, referencer_id.1, reason
+ );
+ }
+ if problems.len() > 20 {
+ println!(" ... and {} more", problems.len() - 20);
+ }
+ }
+
+ Ok(())
+}
+
+fn collect_references_from_object(obj: &Object) -> HashSet<ObjectId> {
+ let mut refs = HashSet::new();
+
+ match obj {
+ Object::Reference(id) => {
+ refs.insert(*id);
+ }
+ Object::Array(array) => {
+ for item in array {
+ refs.extend(collect_references_from_object(item));
+ }
+ }
+ Object::Dictionary(dict) => {
+ refs.extend(collect_references_from_dict(dict));
+ }
+ Object::Stream(stream) => {
+ refs.extend(collect_references_from_dict(&stream.dict));
+ }
+ _ => {}
+ }
+
+ refs
+}
+
+fn collect_references_from_dict(dict: &lopdf::Dictionary) -> HashSet<ObjectId> {
+ let mut refs = HashSet::new();
+
+ for (_key, value) in dict.iter() {
+ refs.extend(collect_references_from_object(value));
+ }
+
+ refs
+}
+
+fn describe_object(obj: &Object) -> String {
+ match obj {
+ Object::Dictionary(d) => {
+ let type_info = d
+ .get(b"Type")
+ .ok()
+ .and_then(|t| t.as_name().ok())
+ .map(|n| String::from_utf8_lossy(n).to_string())
+ .unwrap_or_else(|| "Unknown".to_string());
+ format!("Dictionary (Type: {})", type_info)
+ }
+ _ => format!("{:?}", obj),
+ }
+}
diff --git a/vendor/lopdf/examples/check_raw_objstream.rs b/vendor/lopdf/examples/check_raw_objstream.rs
new file mode 100644
index 000000000..41bbdaf0d
--- /dev/null
+++ b/vendor/lopdf/examples/check_raw_objstream.rs
@@ -0,0 +1,136 @@
+use lopdf::{Document, Object, SaveOptions};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Document {
+ Document::load(path).unwrap()
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Document {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await.unwrap() })
+}
+
+fn main() {
+ println!("Checking raw object stream in saved PDF...\n");
+
+ // Create a simple document
+ let mut doc = Document::with_version("1.5");
+
+ // Add some objects that will be compressed
+ for i in 1..=10 {
+ doc.add_object(Object::Integer(i * 100));
+ }
+
+ // Add catalog
+ let pages_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ });
+
+ let catalog_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save with object streams
+ let options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true,
+ ..Default::default()
+ };
+
+ let filename = "test_raw_objstream.pdf";
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+ std::fs::write(filename, &buffer).unwrap();
+
+ println!("Saved {} bytes to {}", buffer.len(), filename);
+
+ // Now read the raw file and look for object streams
+ println!("\nSearching for object streams in raw file...");
+
+ let file_str = String::from_utf8_lossy(&buffer);
+
+ // Find object streams by looking for "/Type/ObjStm"
+ let mut pos = 0;
+ while let Some(found) = file_str[pos..].find("/Type/ObjStm") {
+ let abs_pos = pos + found;
+ println!("\nFound /Type/ObjStm at position {}", abs_pos);
+
+ // Find the start of this object (look backwards for "obj")
+ if let Some(obj_start) = file_str[..abs_pos].rfind(" obj") {
+ // Extract object number
+ let obj_line_start = file_str[..obj_start].rfind('\n').unwrap_or(0) + 1;
+ let obj_header = &file_str[obj_line_start..obj_start];
+ println!("Object header: {}", obj_header.trim());
+
+ // Look for dictionary end and stream content
+ if let Some(dict_end) = file_str[abs_pos..].find(">>") {
+ let dict_end_pos = abs_pos + dict_end + 2;
+ let dict_content = &file_str[obj_start + 4..dict_end_pos];
+ println!("Dictionary content: {}", dict_content.trim());
+
+ // Check if there's a Filter
+ if dict_content.contains("/Filter") {
+ println!("✓ Has Filter!");
+ } else {
+ println!("✗ No Filter found!");
+ }
+
+ // Check stream content
+ if let Some(stream_start) = file_str[dict_end_pos..].find("stream") {
+ let stream_pos = dict_end_pos + stream_start + 6;
+ if file_str.len() > stream_pos + 2 {
+ let next_char = file_str.as_bytes()[stream_pos + 1];
+ if next_char == b'\n' || next_char == b'\r' {
+ let stream_content_start = stream_pos + 2;
+ // Check first few bytes
+ let preview = &buffer[stream_content_start
+ ..stream_content_start.min(buffer.len()).min(stream_content_start + 20)];
+ println!("First 20 bytes of stream: {:?}", preview);
+
+ // Check if it looks compressed
+ let looks_compressed =
+ preview.iter().any(|&b| b > 127 || (b < 32 && b != b'\n' && b != b'\r'));
+ println!("Looks compressed: {}", looks_compressed);
+ }
+ }
+ }
+ }
+ }
+
+ pos = abs_pos + 10;
+ }
+
+ // Now load it back and check
+ println!("\n\nLoading PDF back...");
+ let loaded = load_document(filename);
+
+ let mut found_objstream = false;
+ for (id, obj) in &loaded.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ found_objstream = true;
+ println!("\nLoaded object stream {} 0 R:", id.0);
+ println!(" Has Filter: {}", stream.dict.get(b"Filter").is_ok());
+ println!(" Dictionary: {:?}", stream.dict);
+ }
+ }
+
+ if !found_objstream {
+ println!("No object streams found in loaded PDF!");
+ }
+}
diff --git a/vendor/lopdf/examples/compress_existing_pdf.rs b/vendor/lopdf/examples/compress_existing_pdf.rs
new file mode 100644
index 000000000..3cce24c44
--- /dev/null
+++ b/vendor/lopdf/examples/compress_existing_pdf.rs
@@ -0,0 +1,107 @@
+use lopdf::{Document, SaveOptions};
+use std::env;
+use std::path::Path;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Get filename from command line or use default
+ let args: Vec<String> = env::args().collect();
+ let input_file = if args.len() > 1 { &args[1] } else { "assets/example.pdf" };
+
+ // Check if file exists
+ if !Path::new(input_file).exists() {
+ eprintln!("Error: File '{}' not found", input_file);
+ eprintln!("Usage: cargo run --example compress_existing_pdf [path/to/pdf]");
+ return Ok(());
+ }
+
+ println!("Loading PDF: {}", input_file);
+
+ // Load the PDF
+ let mut doc = load_document(input_file)?;
+ println!("PDF version: {}", doc.version);
+ println!("Number of objects: {}", doc.objects.len());
+ println!("Number of pages: {}", doc.get_pages().len());
+
+ // Get original file size
+ let original_size = std::fs::metadata(input_file)?.len();
+ println!(
+ "\nOriginal file size: {} bytes ({:.1} KB)",
+ original_size,
+ original_size as f64 / 1024.0
+ );
+
+ // Save without object streams (traditional format)
+ let output_traditional = format!("{}_traditional.pdf", input_file.trim_end_matches(".pdf"));
+ doc.save(&output_traditional)?;
+ let traditional_size = std::fs::metadata(&output_traditional)?.len();
+ println!(
+ "\nTraditional save: {} bytes ({:.1} KB)",
+ traditional_size,
+ traditional_size as f64 / 1024.0
+ );
+
+ // Save with object streams (modern format)
+ let output_modern = format!("{}_compressed.pdf", input_file.trim_end_matches(".pdf"));
+ let mut modern_file = std::fs::File::create(&output_modern)?;
+ doc.save_modern(&mut modern_file)?;
+ drop(modern_file); // Ensure file is closed before reading metadata
+ let modern_size = std::fs::metadata(&output_modern)?.len();
+ println!(
+ "Object streams save: {} bytes ({:.1} KB)",
+ modern_size,
+ modern_size as f64 / 1024.0
+ );
+
+ // Save with custom compression settings
+ let output_custom = format!("{}_max_compressed.pdf", input_file.trim_end_matches(".pdf"));
+ let mut custom_file = std::fs::File::create(&output_custom)?;
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .max_objects_per_stream(200) // More objects per stream
+ .compression_level(9) // Maximum compression
+ .build();
+ doc.save_with_options(&mut custom_file, options)?;
+ drop(custom_file);
+ let custom_size = std::fs::metadata(&output_custom)?.len();
+ println!(
+ "Max compression save: {} bytes ({:.1} KB)",
+ custom_size,
+ custom_size as f64 / 1024.0
+ );
+
+ // Calculate savings
+ println!("\n--- Compression Results ---");
+ let modern_reduction = 100.0 - (modern_size as f64 / original_size as f64 * 100.0);
+ let custom_reduction = 100.0 - (custom_size as f64 / original_size as f64 * 100.0);
+ println!("Object streams reduction: {:.1}%", modern_reduction);
+ println!("Max compression reduction: {:.1}%", custom_reduction);
+
+ // Compare with traditional save
+ let modern_vs_trad = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
+ println!("\nVs traditional re-save: {:.1}% smaller", modern_vs_trad);
+
+ println!("\nOutput files created:");
+ println!(" - {}", output_traditional);
+ println!(" - {}", output_modern);
+ println!(" - {}", output_custom);
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/create.rs b/vendor/lopdf/examples/create.rs
new file mode 100644
index 000000000..4662433dd
--- /dev/null
+++ b/vendor/lopdf/examples/create.rs
@@ -0,0 +1,130 @@
+#[macro_use]
+extern crate lopdf;
+use lopdf::content::{Content, Operation};
+use lopdf::{Document, Object, Stream};
+
+fn main() {
+ // with_version specifes the PDF version this document complies with.
+ let mut doc = Document::with_version("1.5");
+
+ // Object IDs are used for cross referencing in PDF documents.
+ // `lopdf` helps keep track of them for us. They are simple integers.
+ // Calls to `doc.new_object_id` and `doc.add_object` return an object IDs.
+
+ // "Pages" is the root node of the page tree
+ let pages_id = doc.new_object_id();
+
+ // fonts are dictionaries. The type, subtype and basefont tags
+ // are straight out of the PDF reference manual
+ //
+ // The dictionary macro is a helper that allows complex
+ // key, value relationships to be represented in a simpler
+ // visual manner, similar to a match statement.
+ // A dictionary is implemented as an IndexMap of Vec<u8>, and Object
+ let font_id = doc.add_object(dictionary! {
+ // type of dictionary
+ "Type" => "Font",
+ // type of font, type1 is simple postscript font
+ "Subtype" => "Type1",
+ // basefont is postscript name of font for type1 font.
+ // See PDF reference document for more details
+ "BaseFont" => "Courier",
+ });
+
+ // Font dictionaries need to be added into resource dictionaries in order
+ // to be used. Resource dictionaries can contain more than just fonts,
+ // but normally just contains fonts.
+ // Only one resource dictionary is allowed per page tree root
+ let resources_id = doc.add_object(dictionary! {
+ // Fonts are actually triplely nested dictionaries. Fun!
+ "Font" => dictionary! {
+ // F1 is the font name used when writing text.
+ // It must be unique in the document. It does not
+ // have to be F1
+ "F1" => font_id,
+ },
+ });
+
+ // Content is a wrapper struct around an operations struct that contains a vector of operations
+ // The operations struct contains a vector of operations that match up with a particular PDF
+ // operator and operands.
+ // Refer to the PDF spec for more details on these operators and operands.
+ // Note, the operators and operands are specified in a reverse order than they
+ // actually appear in the PDF file itself.
+ let content = Content {
+ operations: vec![
+ // BT begins a text element. it takes no operands
+ Operation::new("BT", vec![]),
+ // Tf specifies the font and font size. Font scaling is complicated in PDFs.
+ // Refer to the PDF spec for more info.
+ // The `into()` methods convert the types into
+ // an enum that represents the basic object types in PDF documents.
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ // Td adjusts the translation components of the text matrix. When used for the first
+ // time after BT, it sets the initial text position on the page.
+ // Note: PDF documents have Y=0 at the bottom. Thus 600 to print text near the top.
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ // Tj prints a string literal to the page. By default, this is black text that is
+ // filled in. There are other operators that can produce various textual effects and
+ // colors
+ Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
+ // ET ends the text element
+ Operation::new("ET", vec![]),
+ ],
+ };
+
+ // Streams are a dictionary followed by a sequence of bytes. What that sequence of bytes
+ // represents, depends on context.
+ // The stream dictionary is set internally by lopdf and normally doesn't
+ // need to be manually nanipulated. It contains keys such as
+ // Length, Filter, DecodeParams, etc.
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+
+ // Page is a dictionary that represents one page of a PDF file.
+ // Its required fields are "Type", "Parent" and "Contents".
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ });
+
+ // Again, pages is the root of the page tree. The ID was already created
+ // at the top of the page, since we needed it to assign to the parent element of the page
+ // dictionary
+ //
+ // These are just the basic requirements for a page tree root object. There are also many
+ // additional entries that can be added to the dictionary if needed. Some of these can also be
+ // defined on the page dictionary itself, and not inherited from the page tree root.
+ let pages = dictionary! {
+ // Type of dictionary
+ "Type" => "Pages",
+ // Vector of page IDs in document. Normally would contain more than one ID and be produced
+ // using a loop of some kind
+ "Kids" => vec![page_id.into()],
+ // Page count
+ "Count" => 1,
+ // ID of resources dictionary, defined earlier
+ "Resources" => resources_id,
+ // a rectangle that defines the boundaries of the physical or digital media. This is the
+ // "Page Size"
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ };
+
+ // using insert() here, instead of add_object() since the id is already known.
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+
+ // Creating document catalog.
+ // There are many more entries allowed in the catalog dictionary.
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ // Root key in trailer is set here to ID of document catalog,
+ // remainder of trailer is set during doc.save().
+ doc.trailer.set("Root", catalog_id);
+ doc.compress();
+
+ // Store file in current working directory.
+ doc.save("example.pdf").unwrap();
+}
diff --git a/vendor/lopdf/examples/create_text_heavy_pdf.rs b/vendor/lopdf/examples/create_text_heavy_pdf.rs
new file mode 100644
index 000000000..070d9e89f
--- /dev/null
+++ b/vendor/lopdf/examples/create_text_heavy_pdf.rs
@@ -0,0 +1,179 @@
+use lopdf::content::{Content, Operation};
+use lopdf::dictionary;
+use lopdf::{Document, Object, Stream};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ println!("Creating a text-heavy PDF with many objects...");
+
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Create many font objects
+ let mut font_ids = Vec::new();
+ for i in 0..20 {
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => format!("Font{}", i),
+ "Encoding" => "WinAnsiEncoding"
+ });
+ font_ids.push(font_id);
+ }
+
+ // Create many metadata objects
+ for i in 0..50 {
+ doc.add_object(dictionary! {
+ "Type" => "Metadata",
+ "Version" => i,
+ "Author" => format!("Author {}", i),
+ "Title" => format!("Document Section {}", i),
+ "Subject" => format!("This is metadata object number {} with some additional text to make it larger", i),
+ "Keywords" => format!("keyword{}, test{}, pdf{}, compression{}", i, i, i, i),
+ "Creator" => "lopdf object streams demo",
+ "Producer" => "lopdf library with object stream support",
+ "CreationDate" => format!("D:2024010{}120000", i % 10)
+ });
+ }
+
+ // Create annotation objects
+ for i in 0..30 {
+ doc.add_object(dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Rect" => vec![100.into(), (100 + i * 20).into(), 200.into(), (120 + i * 20).into()],
+ "Contents" => format!("This is annotation number {} with some descriptive text", i),
+ "Open" => false,
+ "Name" => "Comment",
+ "C" => vec![1.0.into(), 0.0.into(), 0.0.into()]
+ });
+ }
+
+ // Create outline objects (bookmarks)
+ for i in 0..25 {
+ doc.add_object(dictionary! {
+ "Title" => format!("Chapter {}: Introduction to Section {}", i, i),
+ "Count" => 0,
+ "Dest" => format!("section_{}", i)
+ });
+ }
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_ids[0],
+ },
+ });
+
+ // Create page content with lots of text
+ let mut operations = vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![50.into(), 750.into()]),
+ Operation::new("Tj", vec![Object::string_literal("Text-Heavy PDF Compression Demo")]),
+ Operation::new("ET", vec![]),
+ ];
+
+ // Add many text operations
+ for i in 0..50 {
+ operations.extend(vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 10.into()]),
+ Operation::new("Td", vec![50.into(), (700 - i * 10).into()]),
+ Operation::new(
+ "Tj",
+ vec![Object::string_literal(format!(
+ "Line {}: This is a sample text line to demonstrate compression",
+ i
+ ))],
+ ),
+ Operation::new("ET", vec![]),
+ ]);
+ }
+
+ let content = Content { operations };
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save and compare
+ doc.save("text_heavy_traditional.pdf")?;
+ let traditional_size = std::fs::metadata("text_heavy_traditional.pdf")?.len();
+
+ let mut modern_file = std::fs::File::create("text_heavy_compressed.pdf")?;
+ doc.save_modern(&mut modern_file)?;
+ drop(modern_file);
+ let modern_size = std::fs::metadata("text_heavy_compressed.pdf")?.len();
+
+ println!("\nCreated PDF with {} objects", doc.objects.len());
+ println!("\nFile sizes:");
+ println!(
+ "Traditional format: {} bytes ({:.1} KB)",
+ traditional_size,
+ traditional_size as f64 / 1024.0
+ );
+ println!(
+ "With object streams: {} bytes ({:.1} KB)",
+ modern_size,
+ modern_size as f64 / 1024.0
+ );
+
+ let reduction = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
+ println!("\nCompression achieved: {:.1}%", reduction);
+
+ println!("\nFiles created:");
+ println!(" - text_heavy_traditional.pdf");
+ println!(" - text_heavy_compressed.pdf");
+
+ // Analyze the compressed PDF
+ println!("\nAnalyzing compressed PDF:");
+ let compressed_doc = load_document("text_heavy_compressed.pdf")?;
+ let has_objstm = compressed_doc.objects.values().any(|obj| {
+ if let Object::Dictionary(dict) = obj
+ && let Ok(Object::Name(name)) = dict.get(b"Type")
+ {
+ return name == b"ObjStm";
+ }
+ false
+ });
+ println!("Uses object streams: {}", has_objstm);
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/debug_compression_detailed.rs b/vendor/lopdf/examples/debug_compression_detailed.rs
new file mode 100644
index 000000000..4edd51507
--- /dev/null
+++ b/vendor/lopdf/examples/debug_compression_detailed.rs
@@ -0,0 +1,111 @@
+use lopdf::{Document, SaveOptions};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn main() {
+ println!("Debugging object stream compression in detail...\n");
+
+ // Load the user's PDF
+ let pdf_path = "/Users/nicolasdao/Downloads/pdfs/RFQ - SDS WebApp.docx.pdf";
+ println!("Loading PDF: {}", pdf_path);
+
+ let mut doc = match load_document(pdf_path) {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("Failed to load PDF: {}", e);
+ return;
+ }
+ };
+
+ println!("Loaded {} objects", doc.objects.len());
+
+ // Count how many objects can be compressed
+ let mut compressible_count = 0;
+ for (id, obj) in &doc.objects {
+ if id.1 == 0 && lopdf::ObjectStream::can_be_compressed(*id, obj, &doc) {
+ compressible_count += 1;
+ }
+ }
+ println!("Compressible objects: {}", compressible_count);
+
+ // Save with object streams
+ println!("\nSaving with object streams (compression level 6)...");
+ let options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true, // MUST use xref streams with object streams!
+ object_stream_config: lopdf::ObjectStreamConfig {
+ max_objects_per_stream: 100,
+ compression_level: 6,
+ },
+ ..Default::default()
+ };
+
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ println!("Saved {} bytes", buffer.len());
+
+ // Write to file for inspection
+ std::fs::write("debug_compression.pdf", &buffer).unwrap();
+
+ // Load back and check
+ println!("\nLoading back and checking object streams...");
+ let loaded = Document::load_mem(&buffer).unwrap();
+
+ let mut obj_stream_count = 0;
+ let mut obj_stream_with_filter = 0;
+
+ for (id, obj) in &loaded.objects {
+ if let lopdf::Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ obj_stream_count += 1;
+ let has_filter = stream.dict.get(b"Filter").is_ok();
+ if has_filter {
+ obj_stream_with_filter += 1;
+ }
+
+ println!("\nObject Stream {} 0 R:", id.0);
+ println!(" Has Filter: {}", has_filter);
+ if let Ok(n) = stream.dict.get(b"N").and_then(|o| o.as_i64()) {
+ println!(" Contains {} objects", n);
+ }
+ if let Ok(first) = stream.dict.get(b"First").and_then(|o| o.as_i64()) {
+ println!(" First offset: {}", first);
+ }
+ println!(" Content size: {} bytes", stream.content.len());
+
+ // Check if content looks compressed
+ let looks_compressed = stream.content.iter().take(20).any(|&b| b > 127);
+ println!(" Content looks compressed: {}", looks_compressed);
+ }
+ }
+
+ println!("\nSummary:");
+ println!(" Total object streams: {}", obj_stream_count);
+ println!(" Object streams with Filter: {}", obj_stream_with_filter);
+
+ if obj_stream_with_filter < obj_stream_count {
+ println!(
+ "\nWARNING: {} object streams are missing Filter!",
+ obj_stream_count - obj_stream_with_filter
+ );
+ }
+}
diff --git a/vendor/lopdf/examples/debug_compression_full.rs b/vendor/lopdf/examples/debug_compression_full.rs
new file mode 100644
index 000000000..d5584f288
--- /dev/null
+++ b/vendor/lopdf/examples/debug_compression_full.rs
@@ -0,0 +1,524 @@
+use lopdf::{Document, Object, ObjectStream, SaveOptions};
+use std::collections::HashMap;
+use std::env;
+use std::fs::File;
+use std::io::Write;
+
+type ObjectId = (u32, u16);
+type ReferenceLocations = HashMap<ObjectId, (String, ObjectId)>;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let args: Vec<String> = env::args().collect();
+ let input_file = if args.len() > 1 {
+ &args[1]
+ } else {
+ eprintln!("Usage: cargo run --example debug_compression_full <pdf_file>");
+ std::process::exit(1);
+ };
+
+ println!("=== COMPREHENSIVE PDF COMPRESSION DEBUG ===\n");
+
+ // Load original PDF
+ println!("1. Loading original PDF: {}", input_file);
+ let mut doc = load_document(input_file)?;
+ let _original_objects = doc.objects.len();
+
+ // Analyze original structure
+ println!("\n2. Analyzing original PDF structure:");
+ let original_analysis = analyze_document(&doc);
+ print_analysis(&original_analysis);
+
+ // Create debug log file
+ let debug_log_path = format!("{}_debug_log.txt", input_file.trim_end_matches(".pdf"));
+ let mut debug_log = File::create(&debug_log_path)?;
+ writeln!(debug_log, "PDF Compression Debug Log for: {}", input_file)?;
+ writeln!(debug_log, "{}", "=".repeat(80))?;
+
+ // Save with object streams - with detailed logging
+ println!("\n3. Saving with object streams (with detailed logging)...");
+ let options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true,
+ ..Default::default()
+ };
+
+ // Simulate the compression process to log what would happen
+ let mut compressible_objects = Vec::new();
+ let mut non_compressible_objects = Vec::new();
+
+ for (&id, obj) in &doc.objects {
+ let can_compress = ObjectStream::can_be_compressed(id, obj, &doc);
+ let obj_info = format!(
+ "{} {} R: {} - {}",
+ id.0,
+ id.1,
+ obj.type_name()
+ .map(|n| String::from_utf8_lossy(n).to_string())
+ .unwrap_or("Unknown".to_string()),
+ describe_object(obj)
+ );
+
+ if can_compress {
+ compressible_objects.push(obj_info.clone());
+ writeln!(debug_log, "✓ COMPRESSIBLE: {}", obj_info)?;
+ } else {
+ non_compressible_objects.push(obj_info.clone());
+ writeln!(debug_log, "✗ NOT COMPRESSIBLE: {}", obj_info)?;
+
+ // Log why it's not compressible
+ if matches!(obj, Object::Stream(_)) {
+ writeln!(debug_log, " Reason: Is a stream object")?;
+ } else if let Object::Dictionary(dict) = obj
+ && let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && (type_name == b"Page" || type_name == b"Pages")
+ {
+ writeln!(debug_log, " Reason: Is a Page/Pages object")?;
+ }
+
+ // Check if in trailer
+ for (key, value) in doc.trailer.iter() {
+ if value == &Object::Reference(id) {
+ writeln!(
+ debug_log,
+ " Reason: Referenced in trailer[{}]",
+ String::from_utf8_lossy(key)
+ )?;
+ }
+ }
+ }
+ }
+
+ writeln!(debug_log, "\nSummary:")?;
+ writeln!(debug_log, " Compressible objects: {}", compressible_objects.len())?;
+ writeln!(
+ debug_log,
+ " Non-compressible objects: {}",
+ non_compressible_objects.len()
+ )?;
+
+ // Actually save
+ let output_file = format!("{}_compressed.pdf", input_file.trim_end_matches(".pdf"));
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options)?;
+ std::fs::write(&output_file, &buffer)?;
+
+ println!("Saved compressed PDF: {} ({} bytes)", output_file, buffer.len());
+
+ // Load compressed PDF back
+ println!("\n4. Loading compressed PDF back for analysis...");
+ match Document::load_mem(&buffer) {
+ Ok(compressed_doc) => {
+ let compressed_analysis = analyze_document(&compressed_doc);
+
+ println!("\n5. Compressed PDF structure:");
+ print_analysis(&compressed_analysis);
+
+ // Compare structures
+ println!("\n6. Comparing structures:");
+ compare_analyses(&original_analysis, &compressed_analysis, &mut debug_log)?;
+
+ // Verify critical objects
+ println!("\n7. Verifying critical objects in compressed PDF:");
+ verify_critical_objects(&compressed_doc, &mut debug_log)?;
+
+ // Check for orphaned references
+ println!("\n8. Checking for orphaned references:");
+ check_orphaned_references(&compressed_doc, &mut debug_log)?;
+ }
+ Err(e) => {
+ eprintln!("ERROR: Failed to load compressed PDF: {}", e);
+ writeln!(debug_log, "\nERROR: Failed to load compressed PDF: {}", e)?;
+ }
+ }
+
+ println!("\n9. Debug log written to: {}", debug_log_path);
+
+ // Try to use external PDF validator if available
+ println!("\n10. Attempting external validation...");
+ validate_with_external_tools(&output_file);
+
+ Ok(())
+}
+
+#[derive(Debug)]
+struct DocumentAnalysis {
+ total_objects: usize,
+ pages: usize,
+ streams: usize,
+ dictionaries: usize,
+ arrays: usize,
+ object_streams: usize,
+ compressed_objects: usize,
+ page_objects: Vec<(u32, u16)>,
+ content_streams: Vec<(u32, u16)>,
+ fonts: Vec<(u32, u16)>,
+}
+
+fn analyze_document(doc: &Document) -> DocumentAnalysis {
+ let mut analysis = DocumentAnalysis {
+ total_objects: doc.objects.len(),
+ pages: doc.get_pages().len(),
+ streams: 0,
+ dictionaries: 0,
+ arrays: 0,
+ object_streams: 0,
+ compressed_objects: 0,
+ page_objects: Vec::new(),
+ content_streams: Vec::new(),
+ fonts: Vec::new(),
+ };
+
+ // Count compressed objects
+ for xref_entry in doc.reference_table.entries.values() {
+ if let lopdf::xref::XrefEntry::Compressed { .. } = xref_entry {
+ analysis.compressed_objects += 1;
+ }
+ }
+
+ // Analyze objects
+ for (&id, obj) in &doc.objects {
+ match obj {
+ Object::Stream(stream) => {
+ analysis.streams += 1;
+ if let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ analysis.object_streams += 1;
+ }
+ }
+ Object::Dictionary(dict) => {
+ analysis.dictionaries += 1;
+ if let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ {
+ match type_name {
+ b"Page" => analysis.page_objects.push(id),
+ b"Font" => analysis.fonts.push(id),
+ _ => {}
+ }
+ }
+ }
+ Object::Array(_) => analysis.arrays += 1,
+ _ => {}
+ }
+ }
+
+ // Find content streams
+ for &page_id in &analysis.page_objects {
+ if let Ok(page_obj) = doc.get_object(page_id)
+ && let Object::Dictionary(page_dict) = page_obj
+ {
+ match page_dict.get(b"Contents") {
+ Ok(Object::Reference(content_id)) => {
+ analysis.content_streams.push(*content_id);
+ }
+ Ok(Object::Array(contents)) => {
+ for content_ref in contents {
+ if let Object::Reference(content_id) = content_ref {
+ analysis.content_streams.push(*content_id);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ analysis
+}
+
+fn print_analysis(analysis: &DocumentAnalysis) {
+ println!(" Total objects: {}", analysis.total_objects);
+ println!(" Pages: {}", analysis.pages);
+ println!(" Streams: {}", analysis.streams);
+ println!(" Dictionaries: {}", analysis.dictionaries);
+ println!(" Arrays: {}", analysis.arrays);
+ println!(" Object streams: {}", analysis.object_streams);
+ println!(" Compressed objects: {}", analysis.compressed_objects);
+ println!(" Page objects: {:?}", analysis.page_objects);
+ println!(" Content streams: {} found", analysis.content_streams.len());
+ println!(" Fonts: {} found", analysis.fonts.len());
+}
+
+fn describe_object(obj: &Object) -> String {
+ match obj {
+ Object::Null => "Null".to_string(),
+ Object::Boolean(b) => format!("Boolean({})", b),
+ Object::Integer(i) => format!("Integer({})", i),
+ Object::Real(r) => format!("Real({})", r),
+ Object::Name(n) => format!("Name({})", String::from_utf8_lossy(n)),
+ Object::String(_, _) => "String".to_string(),
+ Object::Array(a) => format!("Array[{}]", a.len()),
+ Object::Dictionary(d) => {
+ let keys: Vec<_> = d.iter().take(3).map(|(k, _)| String::from_utf8_lossy(k)).collect();
+ format!("Dict{{{}...}}", keys.join(", "))
+ }
+ Object::Stream(s) => {
+ let keys: Vec<_> = s.dict.iter().take(3).map(|(k, _)| String::from_utf8_lossy(k)).collect();
+ format!("Stream{{dict: {{{}...}}, len: {}}}", keys.join(", "), s.content.len())
+ }
+ Object::Reference(id) => format!("Ref({} {} R)", id.0, id.1),
+ }
+}
+
+fn compare_analyses(original: &DocumentAnalysis, compressed: &DocumentAnalysis, log: &mut File) -> std::io::Result<()> {
+ writeln!(log, "\n=== STRUCTURE COMPARISON ===")?;
+
+ if original.pages != compressed.pages {
+ writeln!(
+ log,
+ "WARNING: Page count changed! {} -> {}",
+ original.pages, compressed.pages
+ )?;
+ }
+
+ if original.page_objects.len() != compressed.page_objects.len() {
+ writeln!(
+ log,
+ "WARNING: Page object count changed! {} -> {}",
+ original.page_objects.len(),
+ compressed.page_objects.len()
+ )?;
+ }
+
+ if original.content_streams.len() != compressed.content_streams.len() {
+ writeln!(
+ log,
+ "WARNING: Content stream count changed! {} -> {}",
+ original.content_streams.len(),
+ compressed.content_streams.len()
+ )?;
+ }
+
+ writeln!(
+ log,
+ "Object count: {} -> {} (compressed {} objects)",
+ original.total_objects, compressed.total_objects, compressed.compressed_objects
+ )?;
+
+ writeln!(log, "Object streams created: {}", compressed.object_streams)?;
+
+ Ok(())
+}
+
+fn verify_critical_objects(doc: &Document, log: &mut File) -> std::io::Result<()> {
+ writeln!(log, "\n=== CRITICAL OBJECT VERIFICATION ===")?;
+
+ // Check all page objects
+ let pages = doc.get_pages();
+ for (num, &page_id) in pages.iter() {
+ match doc.get_object(page_id) {
+ Ok(obj) => {
+ writeln!(
+ log,
+ "Page {} ({} {} R): OK - {}",
+ num,
+ page_id.0,
+ page_id.1,
+ describe_object(obj)
+ )?;
+
+ // Check if it's compressed
+ if let Some(xref) = doc.reference_table.get(page_id.0)
+ && let lopdf::xref::XrefEntry::Compressed { container, index } = xref
+ {
+ writeln!(
+ log,
+ " ERROR: Page is compressed in stream {} at index {}!",
+ container, index
+ )?;
+ }
+
+ // Check page contents
+ if let Object::Dictionary(page_dict) = obj {
+ match page_dict.get(b"Contents") {
+ Ok(Object::Reference(content_id)) => match doc.get_object(*content_id) {
+ Ok(_) => writeln!(log, " Contents {} {} R: OK", content_id.0, content_id.1)?,
+ Err(e) => writeln!(log, " Contents {} {} R: ERROR - {}", content_id.0, content_id.1, e)?,
+ },
+ Ok(Object::Array(contents)) => {
+ writeln!(log, " Contents array with {} elements", contents.len())?;
+ for (i, content_ref) in contents.iter().enumerate() {
+ if let Object::Reference(content_id) = content_ref {
+ match doc.get_object(*content_id) {
+ Ok(_) => writeln!(log, " [{}] {} {} R: OK", i, content_id.0, content_id.1)?,
+ Err(e) => writeln!(
+ log,
+ " [{}] {} {} R: ERROR - {}",
+ i, content_id.0, content_id.1, e
+ )?,
+ }
+ }
+ }
+ }
+ _ => writeln!(log, " Contents: Unexpected type")?,
+ }
+ }
+ }
+ Err(e) => {
+ writeln!(log, "Page {} ({} {} R): ERROR - {}", num, page_id.0, page_id.1, e)?;
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn check_orphaned_references(doc: &Document, log: &mut File) -> std::io::Result<()> {
+ writeln!(log, "\n=== ORPHANED REFERENCE CHECK ===")?;
+
+ let mut all_references = HashMap::new();
+
+ // Collect all references
+ for (id, obj) in &doc.objects {
+ collect_references(obj, &mut all_references, *id);
+ }
+
+ // Check trailer references
+ for (_key, value) in doc.trailer.iter() {
+ if let Object::Reference(ref_id) = value {
+ all_references.insert(*ref_id, ("trailer".to_string(), (0, 0)));
+ }
+ }
+
+ // Check if all referenced objects exist
+ let mut orphaned_count = 0;
+ for (ref_id, (location, from_id)) in &all_references {
+ match doc.get_object(*ref_id) {
+ Ok(_) => {
+ // Check if it's in a compressed stream
+ if let Some(xref) = doc.reference_table.get(ref_id.0)
+ && let lopdf::xref::XrefEntry::Compressed { container, .. } = xref
+ {
+ // Make sure the container exists
+ if doc.get_object((*container, 0)).is_err() {
+ writeln!(
+ log,
+ "ERROR: Reference {} {} R from {} ({} {} R) points to compressed object in non-existent stream {}!",
+ ref_id.0, ref_id.1, location, from_id.0, from_id.1, container
+ )?;
+ orphaned_count += 1;
+ }
+ }
+ }
+ Err(_) => {
+ writeln!(
+ log,
+ "ERROR: Orphaned reference {} {} R from {} ({} {} R)",
+ ref_id.0, ref_id.1, location, from_id.0, from_id.1
+ )?;
+ orphaned_count += 1;
+ }
+ }
+ }
+
+ writeln!(log, "\nTotal references checked: {}", all_references.len())?;
+ writeln!(log, "Orphaned references: {}", orphaned_count)?;
+
+ Ok(())
+}
+
+fn collect_references(obj: &Object, refs: &mut ReferenceLocations, from_id: ObjectId) {
+ match obj {
+ Object::Reference(ref_id) => {
+ refs.insert(*ref_id, ("direct".to_string(), from_id));
+ }
+ Object::Array(array) => {
+ for (i, item) in array.iter().enumerate() {
+ if let Object::Reference(ref_id) = item {
+ refs.insert(*ref_id, (format!("array[{}]", i), from_id));
+ }
+ collect_references(item, refs, from_id);
+ }
+ }
+ Object::Dictionary(dict) => {
+ for (key, value) in dict.iter() {
+ if let Object::Reference(ref_id) = value {
+ refs.insert(*ref_id, (format!("dict[{}]", String::from_utf8_lossy(key)), from_id));
+ }
+ collect_references(value, refs, from_id);
+ }
+ }
+ Object::Stream(stream) => {
+ for (key, value) in stream.dict.iter() {
+ if let Object::Reference(ref_id) = value {
+ refs.insert(
+ *ref_id,
+ (format!("stream.dict[{}]", String::from_utf8_lossy(key)), from_id),
+ );
+ }
+ collect_references(value, refs, from_id);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn validate_with_external_tools(pdf_path: &str) {
+ // Try to use pdfinfo if available
+ println!("Trying pdfinfo...");
+ match std::process::Command::new("pdfinfo").arg(pdf_path).output() {
+ Ok(output) => {
+ if output.status.success() {
+ println!("✓ pdfinfo validation passed");
+ } else {
+ println!("✗ pdfinfo validation failed:");
+ println!("{}", String::from_utf8_lossy(&output.stderr));
+ }
+ }
+ Err(_) => {
+ println!(" pdfinfo not available");
+ }
+ }
+
+ // Try to use qpdf if available
+ println!("\nTrying qpdf --check...");
+ match std::process::Command::new("qpdf").args(["--check", pdf_path]).output() {
+ Ok(output) => {
+ if output.status.success() {
+ println!("✓ qpdf validation passed");
+ } else {
+ println!("✗ qpdf validation failed:");
+ println!("{}", String::from_utf8_lossy(&output.stderr));
+ }
+ }
+ Err(_) => {
+ println!(" qpdf not available");
+ }
+ }
+
+ // Try to use mutool if available
+ println!("\nTrying mutool info...");
+ match std::process::Command::new("mutool").args(["info", pdf_path]).output() {
+ Ok(output) => {
+ if output.status.success() {
+ println!("✓ mutool validation passed");
+ } else {
+ println!("✗ mutool validation failed:");
+ println!("{}", String::from_utf8_lossy(&output.stderr));
+ }
+ }
+ Err(_) => {
+ println!(" mutool not available");
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/debug_object_stream.rs b/vendor/lopdf/examples/debug_object_stream.rs
new file mode 100644
index 000000000..22c945a51
--- /dev/null
+++ b/vendor/lopdf/examples/debug_object_stream.rs
@@ -0,0 +1,66 @@
+use lopdf::{Object, ObjectStream};
+
+fn main() {
+ println!("Testing Object Stream creation...\n");
+
+ // Create a simple object stream with a few objects
+ let mut obj_stream = ObjectStream::builder().max_objects(10).compression_level(6).build();
+
+ // Add some simple objects
+ obj_stream.add_object((1, 0), Object::Integer(42)).unwrap();
+ obj_stream
+ .add_object((2, 0), Object::String(b"Hello".to_vec(), lopdf::StringFormat::Literal))
+ .unwrap();
+ obj_stream.add_object((3, 0), Object::Boolean(true)).unwrap();
+
+ println!("Added {} objects to stream", obj_stream.object_count());
+
+ // Build the stream content
+ match obj_stream.build_stream_content() {
+ Ok(content) => {
+ println!("\nStream content built successfully:");
+ println!("Content size: {} bytes", content.len());
+
+ // Show the content
+ if let Ok(content_str) = std::str::from_utf8(&content) {
+ println!("\nContent (first 200 chars):");
+ println!("{}", &content_str[..content_str.len().min(200)]);
+ } else {
+ println!(
+ "\nRaw content (first 100 bytes): {:?}",
+ &content[..content.len().min(100)]
+ );
+ }
+
+ // Try to create the stream object
+ match obj_stream.to_stream_object() {
+ Ok(stream) => {
+ println!("\n\nStream object created successfully!");
+ println!("Dictionary: {:?}", stream.dict);
+ println!("Compressed: {}", stream.dict.get(b"Filter").is_ok());
+ println!("Content length: {}", stream.content.len());
+
+ // Try to decompress and verify
+ match stream.decompressed_content() {
+ Ok(decompressed) => {
+ println!("\nDecompressed successfully!");
+ println!("Decompressed size: {} bytes", decompressed.len());
+ if let Ok(decomp_str) = std::str::from_utf8(&decompressed) {
+ println!("Decompressed content:\n{}", decomp_str);
+ }
+ }
+ Err(e) => {
+ println!("\nERROR: Failed to decompress: {}", e);
+ }
+ }
+ }
+ Err(e) => {
+ println!("\nERROR: Failed to create stream object: {}", e);
+ }
+ }
+ }
+ Err(e) => {
+ println!("ERROR: Failed to build stream content: {}", e);
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/debug_save_with_objstreams.rs b/vendor/lopdf/examples/debug_save_with_objstreams.rs
new file mode 100644
index 000000000..2334a6bbc
--- /dev/null
+++ b/vendor/lopdf/examples/debug_save_with_objstreams.rs
@@ -0,0 +1,86 @@
+use lopdf::{Document, Object, SaveOptions, dictionary};
+use std::io::Write;
+
+fn main() {
+ println!("Debugging save_with_object_streams...\n");
+
+ // Create a simple document
+ let mut doc = Document::with_version("1.5");
+
+ // Add some simple objects that can be compressed
+ let obj1_id = doc.add_object(Object::Integer(42));
+ let obj2_id = doc.add_object(Object::String(b"Hello".to_vec(), lopdf::StringFormat::Literal));
+ let obj3_id = doc.add_object(dictionary! {
+ "Type" => "TestObject",
+ "Value" => 123
+ });
+
+ println!("Created objects:");
+ println!(" {} 0 R: Integer", obj1_id.0);
+ println!(" {} 0 R: String", obj2_id.0);
+ println!(" {} 0 R: Dictionary", obj3_id.0);
+
+ // Add required catalog structure
+ let pages_id = doc.add_object(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ });
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ println!("\nSaving with object streams...");
+
+ // Save with object streams
+ let options = SaveOptions {
+ use_object_streams: true,
+ ..Default::default()
+ };
+
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ println!("Saved {} bytes", buffer.len());
+
+ // Write to file for inspection
+ let mut file = std::fs::File::create("debug_objstream_save.pdf").unwrap();
+ file.write_all(&buffer).unwrap();
+
+ // Load it back and check
+ println!("\nLoading back and analyzing...");
+ let loaded = Document::load_mem(&buffer).unwrap();
+
+ println!("Loaded {} objects", loaded.objects.len());
+
+ // Find object streams
+ for (id, obj) in &loaded.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ println!("\nFound object stream {} 0 R:", id.0);
+ println!(" Dictionary: {:?}", stream.dict);
+ println!(" Has Filter: {}", stream.dict.get(b"Filter").is_ok());
+ println!(" Content size: {} bytes", stream.content.len());
+
+ // Check if it looks compressed
+ let looks_compressed = stream.content.iter().take(10).any(|&b| !(32..=127).contains(&b));
+ println!(" Content looks compressed: {}", looks_compressed);
+
+ if !looks_compressed {
+ println!(
+ " First 50 bytes: {:?}",
+ &stream.content[..stream.content.len().min(50)]
+ );
+ }
+ }
+ }
+
+ println!("\nDone! Check debug_objstream_save.pdf");
+}
diff --git a/vendor/lopdf/examples/decompression_bomb.rs b/vendor/lopdf/examples/decompression_bomb.rs
new file mode 100644
index 000000000..6f1a3f462
--- /dev/null
+++ b/vendor/lopdf/examples/decompression_bomb.rs
@@ -0,0 +1,123 @@
+//! Demonstrates bounding stream decompression to reject decompression bombs.
+//!
+//! Run with: cargo run --example decompression_bomb
+//!
+//! A decompression bomb is a tiny compressed stream that inflates to an enormous
+//! size. This example builds one and decodes it with a size limit, for a direct
+//! stream, a chained-filter stream, and a bomb embedded in a PDF that is decoded
+//! during `Document::load`.
+
+use std::io::Write;
+use std::time::Instant;
+
+use flate2::Compression;
+use flate2::write::ZlibEncoder;
+use lopdf::{Dictionary, Document, LoadOptions, Object, Stream};
+
+const MIB: usize = 1024 * 1024;
+
+/// A zlib stream that decodes to `target` zero-bytes, built by streaming zeros
+/// through the compressor so this process never holds `target` bytes at once.
+fn flate_bomb(target: usize) -> Vec<u8> {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ let zeros = [0u8; 64 * 1024];
+ let mut remaining = target;
+ while remaining > 0 {
+ let n = remaining.min(zeros.len());
+ encoder.write_all(&zeros[..n]).unwrap();
+ remaining -= n;
+ }
+ encoder.finish().unwrap()
+}
+
+fn zlib_compress(data: &[u8]) -> Vec<u8> {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ encoder.write_all(data).unwrap();
+ encoder.finish().unwrap()
+}
+
+fn main() {
+ println!("== lopdf decompression-bomb guard ==\n");
+
+ // ---- 1. A single-filter bomb -----------------------------------------
+ let logical_output = 256 * MIB;
+ let bomb = flate_bomb(logical_output);
+ println!(
+ "Built a FlateDecode bomb: {} bytes compressed -> {} bytes decompressed ({}x amplification).",
+ bomb.len(),
+ logical_output,
+ logical_output / bomb.len().max(1)
+ );
+
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "FlateDecode");
+ let stream = Stream::new(dict, bomb.clone());
+
+ let limit = 8 * MIB;
+ let start = Instant::now();
+ match stream.decompressed_content_with_limit(limit) {
+ Ok(data) => println!(" UNEXPECTED: decompressed {} bytes", data.len()),
+ Err(e) => println!(
+ " decompressed_content_with_limit({} MiB) rejected it in {:?}: {e}",
+ limit / MIB,
+ start.elapsed()
+ ),
+ }
+ println!(
+ " (The default decompressed_content() has NO limit and would allocate all {} MiB.)\n",
+ logical_output / MIB
+ );
+
+ // ---- 2. A chained-filter bomb: [FlateDecode FlateDecode] -------------
+ // Each layer amplifies ~1000x, so two layers reach ~1,000,000x. The guard
+ // bounds every layer, so the bomb is caught at the second one.
+ let inner = flate_bomb(256 * MIB);
+ let outer = zlib_compress(&inner);
+ let mut dict = Dictionary::new();
+ dict.set("Filter", vec![Object::from("FlateDecode"), Object::from("FlateDecode")]);
+ let chained = Stream::new(dict, outer.clone());
+ println!(
+ "Built a chained [FlateDecode FlateDecode] bomb: {} bytes -> ~256 MiB after two layers.",
+ outer.len()
+ );
+ match chained.decompressed_content_with_limit(limit) {
+ Ok(data) => println!(" UNEXPECTED: decompressed {} bytes", data.len()),
+ Err(e) => println!(" rejected at a filter layer with an {} MiB limit: {e}\n", limit / MIB),
+ }
+
+ // ---- 3. A bomb inside a PDF's cross-reference stream ----------------
+ // The xref stream is decoded during Document::load to build the xref
+ // table, so the limit is supplied through LoadOptions.
+ let pdf = xref_stream_bomb_pdf(&bomb);
+ println!("Loading a PDF whose cross-reference stream is the bomb...");
+ match Document::load_mem(&pdf) {
+ Ok(_) => println!(" load_mem (no limit): parsed after decoding the full output"),
+ Err(e) => println!(" load_mem (no limit): {e}"),
+ }
+ match Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(limit)) {
+ Ok(_) => println!(" UNEXPECTED: guarded load succeeded"),
+ Err(e) => println!(
+ " load_mem_with_options(max_decompressed_size = {} MiB): {e}",
+ limit / MIB
+ ),
+ }
+}
+
+fn xref_stream_bomb_pdf(bomb: &[u8]) -> Vec<u8> {
+ let mut pdf = Vec::new();
+ pdf.extend_from_slice(b"%PDF-1.5\n");
+ let obj_offset = pdf.len();
+ pdf.extend_from_slice(b"1 0 obj\n");
+ pdf.extend_from_slice(
+ format!(
+ "<< /Type /XRef /Size 1 /W [1 1 1] /Root 1 0 R /Filter /FlateDecode /Length {} >>\n",
+ bomb.len()
+ )
+ .as_bytes(),
+ );
+ pdf.extend_from_slice(b"stream\n");
+ pdf.extend_from_slice(bomb);
+ pdf.extend_from_slice(b"\nendstream\nendobj\n");
+ pdf.extend_from_slice(format!("startxref\n{obj_offset}\n%%EOF").as_bytes());
+ pdf
+}
diff --git a/vendor/lopdf/examples/decrypt.rs b/vendor/lopdf/examples/decrypt.rs
new file mode 100644
index 000000000..3b02e8043
--- /dev/null
+++ b/vendor/lopdf/examples/decrypt.rs
@@ -0,0 +1,60 @@
+use lopdf::Document;
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(
+ args.len() >= 3,
+ "Not enough arguments: input_file output_file <password>"
+ );
+ let input_file = &args[1];
+ let output_file = &args[2];
+ let password = if args.len() >= 4 { &args[3] } else { "" };
+
+ let mut doc = Document::load(input_file).unwrap();
+
+ // Check if the document is actually encrypted.
+ if doc.encryption_state.is_none() && !doc.is_encrypted() {
+ println!("nothing to be done");
+ return;
+ }
+
+ // Decrypt the document.
+ if doc.is_encrypted() {
+ doc.decrypt(password).unwrap();
+ }
+
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(
+ args.len() >= 3,
+ "Not enough arguments: input_file output_file <password>"
+ );
+ let input_file = &args[1];
+ let output_file = &args[2];
+ let password = if args.len() >= 4 { &args[3] } else { "" };
+
+ let mut doc = Document::load(input_file).await.unwrap();
+
+ // Check if the document is actually encrypted.
+ if doc.encryption_state.is_none() && !doc.is_encrypted() {
+ println!("nothing to be done");
+ return;
+ }
+
+ // Decrypt the document.
+ if doc.is_encrypted() {
+ doc.decrypt(password).unwrap();
+ }
+
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
diff --git a/vendor/lopdf/examples/delete_outlines.rs b/vendor/lopdf/examples/delete_outlines.rs
new file mode 100644
index 000000000..41dd19440
--- /dev/null
+++ b/vendor/lopdf/examples/delete_outlines.rs
@@ -0,0 +1,46 @@
+use std::env;
+use std::path::{Path, PathBuf};
+
+use lopdf::Document;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let input = match env::args_os().nth(1) {
+ Some(input) => PathBuf::from(input),
+ None => panic!("Please provide a PDF file as first argument"),
+ };
+
+ let output = output_path(&input);
+ let mut doc = load_document(&input)?;
+ doc.delete_outlines()?;
+ doc.save(&output)?;
+
+ println!("Saved {}", output.display());
+
+ Ok(())
+}
+
+fn output_path(input: &Path) -> PathBuf {
+ let stem = input
+ .file_stem()
+ .expect("input file has no file stem")
+ .to_string_lossy();
+
+ input.with_file_name(format!("{stem}-NOTOC.pdf"))
+}
+
+#[cfg(not(feature = "async"))]
+fn load_document<P: AsRef<Path>>(path: P) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document<P: AsRef<Path>>(path: P) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
diff --git a/vendor/lopdf/examples/encrypt.rs b/vendor/lopdf/examples/encrypt.rs
new file mode 100644
index 000000000..58089b8c2
--- /dev/null
+++ b/vendor/lopdf/examples/encrypt.rs
@@ -0,0 +1,252 @@
+use lopdf::encryption::crypt_filters::{Aes128CryptFilter, Aes256CryptFilter, CryptFilter};
+use lopdf::{Document, EncryptionState, EncryptionVersion, Permissions};
+use rand::RngExt as _;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(args.len() >= 4, "Not enough arguments: input_file output_file version");
+ let input_file = &args[1];
+ let output_file = &args[2];
+ let version = args[3].parse::<i64>().unwrap_or(0);
+
+ let mut doc = Document::load(input_file).unwrap();
+ let permissions = Permissions::PRINTABLE
+ | Permissions::COPYABLE
+ | Permissions::COPYABLE_FOR_ACCESSIBILITY
+ | Permissions::PRINTABLE_IN_HIGH_QUALITY;
+ let mut file_encryption_key = [0u8; 32];
+
+ let requested_version = match version {
+ 1 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ EncryptionVersion::V1 {
+ document: &doc,
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ 2 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password key_length"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+ let key_length = if args.len() > 6 {
+ args[6].parse::<usize>().unwrap_or(40)
+ } else {
+ 40
+ };
+
+ EncryptionVersion::V2 {
+ document: &doc,
+ owner_password,
+ user_password,
+ key_length,
+ permissions,
+ }
+ }
+ 4 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes128CryptFilter);
+
+ EncryptionVersion::V4 {
+ document: &doc,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ 5 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ EncryptionVersion::V5 {
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ file_encryption_key: &file_encryption_key,
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ _ => {
+ println!("unsupported version {version}");
+ return;
+ }
+ };
+
+ let state = EncryptionState::try_from(requested_version).unwrap();
+
+ // Ensure the document is decrypted.
+ if doc.is_encrypted() {
+ println!("nothing to be done");
+ return;
+ }
+
+ // Encrypt the document.
+ doc.encrypt(&state).unwrap();
+
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(args.len() >= 4, "Not enough arguments: input_file output_file version");
+ let input_file = &args[1];
+ let output_file = &args[2];
+ let version = args[3].parse::<i64>().unwrap_or(0);
+
+ let mut doc = Document::load(input_file).await.unwrap();
+ let permissions = Permissions::PRINTABLE
+ | Permissions::COPYABLE
+ | Permissions::COPYABLE_FOR_ACCESSIBILITY
+ | Permissions::PRINTABLE_IN_HIGH_QUALITY;
+ let mut file_encryption_key = [0u8; 32];
+
+ let requested_version = match version {
+ 1 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ EncryptionVersion::V1 {
+ document: &doc,
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ 2 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password key_length"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+ let key_length = if args.len() > 6 {
+ args[6].parse::<usize>().unwrap_or(40)
+ } else {
+ 40
+ };
+
+ EncryptionVersion::V2 {
+ document: &doc,
+ owner_password,
+ user_password,
+ key_length,
+ permissions,
+ }
+ }
+ 4 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes128CryptFilter);
+
+ EncryptionVersion::V4 {
+ document: &doc,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ 5 => {
+ assert!(
+ args.len() >= 6,
+ "Not enough arguments: input_file output_file 1 owner_password user_password"
+ );
+
+ let owner_password = &args[4];
+ let user_password = &args[5];
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ EncryptionVersion::V5 {
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ file_encryption_key: &file_encryption_key,
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password,
+ user_password,
+ permissions,
+ }
+ }
+ _ => {
+ println!("unsupported version {version}");
+ return;
+ }
+ };
+
+ let state = EncryptionState::try_from(requested_version).unwrap();
+
+ // Ensure the document is decrypted.
+ if doc.is_encrypted() {
+ println!("nothing to be done");
+ return;
+ }
+
+ // Encrypt the document.
+ doc.encrypt(&state).unwrap();
+
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
diff --git a/vendor/lopdf/examples/extract_text.rs b/vendor/lopdf/examples/extract_text.rs
new file mode 100644
index 000000000..dd2bb77e6
--- /dev/null
+++ b/vendor/lopdf/examples/extract_text.rs
@@ -0,0 +1,189 @@
+use std::collections::BTreeMap;
+use std::fmt::Debug;
+use std::fs::File;
+use std::io::{Error, ErrorKind, Write};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+use clap::Parser;
+use lopdf::{Document, LoadOptions, Object};
+use rayon::iter::{IntoParallelIterator, ParallelIterator};
+use serde::{Deserialize, Serialize};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+static IGNORE: &[&[u8]] = &[
+ b"Length",
+ b"BBox",
+ b"FormType",
+ b"Matrix",
+ b"Type",
+ b"XObject",
+ b"Subtype",
+ b"Filter",
+ b"ColorSpace",
+ b"Width",
+ b"Height",
+ b"BitsPerComponent",
+ b"Length1",
+ b"Length2",
+ b"Length3",
+ b"PTEX.FileName",
+ b"PTEX.PageNumber",
+ b"PTEX.InfoDict",
+ b"FontDescriptor",
+ b"ExtGState",
+ b"MediaBox",
+ b"Annot",
+];
+
+#[derive(Debug, Deserialize, Serialize)]
+struct PdfText {
+ text: BTreeMap<u32, Vec<String>>, // Key is page number
+ errors: Vec<String>,
+}
+
+#[derive(Parser, Debug)]
+#[clap(
+ author,
+ version,
+ about,
+ long_about = "Extract TOC and write to file.",
+ arg_required_else_help = true
+)]
+pub struct Args {
+ pub pdf_path: PathBuf,
+
+ /// Optional output directory. If omitted the directory of the PDF file will be used.
+ #[clap(short, long)]
+ pub output: Option<PathBuf>,
+
+ /// Optional pretty print output.
+ #[clap(short, long)]
+ pub pretty: bool,
+
+ /// Optional password for encrypted PDFs
+ #[clap(long, default_value_t = String::from(""))]
+ pub password: String,
+}
+
+impl Args {
+ pub fn parse_args() -> Self {
+ Args::parse()
+ }
+}
+
+fn filter_func(object_id: (u32, u16), object: &mut Object) -> Option<((u32, u16), Object)> {
+ if IGNORE.contains(&object.type_name().unwrap_or_default()) {
+ return None;
+ }
+ if let Ok(d) = object.as_dict_mut() {
+ d.remove(b"Producer");
+ d.remove(b"ModDate");
+ d.remove(b"Creator");
+ d.remove(b"ProcSet");
+ d.remove(b"Procset");
+ d.remove(b"XObject");
+ d.remove(b"MediaBox");
+ d.remove(b"Annots");
+ if d.is_empty() {
+ return None;
+ }
+ }
+ Some((object_id, object.to_owned()))
+}
+
+#[cfg(not(feature = "async"))]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Document::load_with_options(path, LoadOptions::with_filter(filter_func)).map_err(|e| Error::other(e.to_string()))
+}
+
+#[cfg(feature = "async")]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Builder::new_current_thread().build().unwrap().block_on(async move {
+ Document::load_with_options(path, LoadOptions::with_filter(filter_func))
+ .await
+ .map_err(|e| Error::other(e.to_string()))
+ })
+}
+
+fn get_pdf_text(doc: &Document) -> Result<PdfText, Error> {
+ let mut pdf_text: PdfText = PdfText {
+ text: BTreeMap::new(),
+ errors: Vec::new(),
+ };
+ let pages: Vec<Result<(u32, Vec<String>), Error>> = doc
+ .get_pages()
+ .into_par_iter()
+ .map(
+ |(page_num, page_id): (u32, (u32, u16))| -> Result<(u32, Vec<String>), Error> {
+ let text = doc.extract_text(&[page_num]).map_err(|e| {
+ Error::other(format!(
+ "Failed to extract text from page {page_num} id={page_id:?}: {e:}"
+ ))
+ })?;
+ Ok((
+ page_num,
+ text.split('\n')
+ .map(|s| s.trim_end().to_string())
+ .collect::<Vec<String>>(),
+ ))
+ },
+ )
+ .collect();
+ for page in pages {
+ match page {
+ Ok((page_num, lines)) => {
+ pdf_text.text.insert(page_num, lines);
+ }
+ Err(e) => {
+ pdf_text.errors.push(e.to_string());
+ }
+ }
+ }
+ Ok(pdf_text)
+}
+
+fn pdf2text<P: AsRef<Path> + Debug>(path: P, output: P, pretty: bool, password: &str) -> Result<(), Error> {
+ println!("Load {path:?}");
+ let mut doc = load_pdf(&path)?;
+ if doc.is_encrypted() {
+ doc.decrypt(password)
+ .map_err(|_err| Error::new(ErrorKind::InvalidInput, "Failed to decrypt"))?;
+ }
+ let text = get_pdf_text(&doc)?;
+ if !text.errors.is_empty() {
+ eprintln!("{path:?} has {} errors:", text.errors.len());
+ for error in &text.errors[..text.errors.len().min(10)] {
+ eprintln!("{error:?}");
+ }
+ }
+ let data = match pretty {
+ true => serde_json::to_string_pretty(&text).unwrap(),
+ false => serde_json::to_string(&text).unwrap(),
+ };
+ println!("Write {output:?}");
+ let mut f = File::create(output)?;
+ f.write_all(data.as_bytes())?;
+ Ok(())
+}
+
+fn main() -> Result<(), Error> {
+ let args = Args::parse_args();
+
+ let start_time = Instant::now();
+ let pdf_path = PathBuf::from(shellexpand::full(args.pdf_path.to_str().unwrap()).unwrap().to_string());
+ let output = match args.output {
+ Some(o) => o.join(pdf_path.file_name().unwrap()),
+ None => args.pdf_path,
+ };
+ let mut output = PathBuf::from(shellexpand::full(output.to_str().unwrap()).unwrap().to_string());
+ output.set_extension("text");
+ pdf2text(&pdf_path, &output, args.pretty, &args.password)?;
+ println!(
+ "Done after {:.1} seconds.",
+ Instant::now().duration_since(start_time).as_secs_f64()
+ );
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/extract_toc.rs b/vendor/lopdf/examples/extract_toc.rs
new file mode 100644
index 000000000..0bcaa8d45
--- /dev/null
+++ b/vendor/lopdf/examples/extract_toc.rs
@@ -0,0 +1,142 @@
+use std::fmt::Debug;
+use std::fs::File;
+use std::io::{Error, ErrorKind, Write};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+use clap::Parser;
+use lopdf::{Document, LoadOptions, Object};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+static IGNORE: &[&[u8]] = &[
+ b"Length",
+ b"BBox",
+ b"FormType",
+ b"Matrix",
+ b"Resources",
+ b"Type",
+ b"XObject",
+ b"Subtype",
+ b"Filter",
+ b"ColorSpace",
+ b"Width",
+ b"Height",
+ b"BitsPerComponent",
+ b"Length1",
+ b"Length2",
+ b"Length3",
+ b"PTEX.FileName",
+ b"PTEX.PageNumber",
+ b"PTEX.InfoDict",
+ b"FontDescriptor",
+ b"ExtGState",
+ b"Font",
+ b"MediaBox",
+ b"Annot",
+];
+
+#[derive(Parser, Debug)]
+#[clap(
+ author,
+ version,
+ about,
+ long_about = "Extract TOC and write to file.",
+ arg_required_else_help = true
+)]
+pub struct Args {
+ pub pdf_path: PathBuf,
+
+ /// Optional output directory. If omitted the directory of the PDF file will be used.
+ #[clap(short, long)]
+ pub output: Option<PathBuf>,
+
+ /// Optional pretty print output.
+ #[clap(short, long)]
+ pub pretty: bool,
+}
+
+impl Args {
+ pub fn parse_args() -> Self {
+ Args::parse()
+ }
+}
+
+fn filter_func(object_id: (u32, u16), object: &mut Object) -> Option<((u32, u16), Object)> {
+ if IGNORE.contains(&object.type_name().unwrap_or_default()) {
+ return None;
+ }
+ if let Ok(d) = object.as_dict_mut() {
+ d.remove(b"Font");
+ d.remove(b"Resources");
+ d.remove(b"Producer");
+ d.remove(b"ModDate");
+ d.remove(b"Creator");
+ d.remove(b"ProcSet");
+ d.remove(b"Procset");
+ d.remove(b"XObject");
+ d.remove(b"MediaBox");
+ d.remove(b"Annots");
+ if d.is_empty() {
+ return None;
+ }
+ }
+ Some((object_id, object.to_owned()))
+}
+
+#[cfg(not(feature = "async"))]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Document::load_with_options(path, LoadOptions::with_filter(filter_func)).map_err(|e| Error::other(e.to_string()))
+}
+
+#[cfg(feature = "async")]
+fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
+ Builder::new_current_thread().build().unwrap().block_on(async move {
+ Document::load_with_options(path, LoadOptions::with_filter(filter_func))
+ .await
+ .map_err(|e| Error::other(e.to_string()))
+ })
+}
+
+fn pdf2toc<P: AsRef<Path> + Debug>(path: P, output: P, pretty: bool) -> Result<(), Error> {
+ println!("Load {path:?}");
+ let doc = load_pdf(&path)?;
+ if doc.is_encrypted() {
+ return Err(Error::new(ErrorKind::InvalidInput, "Password missing!"));
+ }
+ let toc = doc.get_toc().map_err(|e| Error::other(e.to_string()))?;
+ if !toc.errors.is_empty() {
+ eprintln!("{path:?} has {} errors:", toc.errors.len());
+ for error in &toc.errors[..toc.errors.len().min(10)] {
+ eprintln!("{error:?}");
+ }
+ }
+ let data = match pretty {
+ true => serde_json::to_string_pretty(&toc).unwrap(),
+ false => serde_json::to_string(&toc).unwrap(),
+ };
+ println!("Write {output:?}");
+ let mut f = File::create(output)?;
+ f.write_all(data.as_bytes())?;
+ Ok(())
+}
+
+fn main() -> Result<(), Error> {
+ let args = Args::parse_args();
+
+ let start_time = Instant::now();
+ let pdf_path = PathBuf::from(shellexpand::full(args.pdf_path.to_str().unwrap()).unwrap().to_string());
+ let output = match args.output {
+ Some(o) => o.join(pdf_path.file_name().unwrap()),
+ None => args.pdf_path,
+ };
+ let mut output = PathBuf::from(shellexpand::full(output.to_str().unwrap()).unwrap().to_string());
+ output.set_extension("toc");
+ pdf2toc(&pdf_path, &output, args.pretty)?;
+ println!(
+ "Done after {:.1} seconds.",
+ Instant::now().duration_since(start_time).as_secs_f64()
+ );
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/final_compression_test.rs b/vendor/lopdf/examples/final_compression_test.rs
new file mode 100644
index 000000000..cd4bd3188
--- /dev/null
+++ b/vendor/lopdf/examples/final_compression_test.rs
@@ -0,0 +1,149 @@
+use lopdf::{Document, Object, SaveOptions};
+
+fn main() {
+ println!("Final Object Stream Compression Test\n");
+ println!("{}", "=".repeat(60));
+
+ // Create test document with various object types
+ let mut doc = Document::with_version("1.5");
+
+ // Add some compressible objects (fonts, annotations, etc.)
+ let font1 = doc.add_object(lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ });
+
+ let font2 = doc.add_object(lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Times-Roman"
+ });
+
+ // Add a page (should NOT be compressed)
+ let page_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Page",
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => lopdf::Object::Array(vec![]),
+ "Resources" => lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => font1,
+ "F2" => font2
+ }
+ }
+ });
+
+ // Add pages tree (should NOT be compressed)
+ let pages_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1
+ });
+
+ // Add catalog (should NOT be compressed - it's in trailer)
+ let catalog_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Add more compressible objects
+ for i in 0..10 {
+ doc.add_object(lopdf::dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Contents" => format!("Annotation {}", i)
+ });
+ }
+
+ println!("Created test document with:");
+ println!(" - 2 Font objects (should be compressed)");
+ println!(" - 1 Page object (should NOT be compressed)");
+ println!(" - 1 Pages object (should NOT be compressed)");
+ println!(" - 1 Catalog object (should NOT be compressed)");
+ println!(" - 10 Annotation objects (should be compressed)");
+
+ // Save with object streams
+ let options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true,
+ ..Default::default()
+ };
+
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ println!("\nSaved with object streams: {} bytes", buffer.len());
+
+ // Load back and analyze
+ let loaded = Document::load_mem(&buffer).unwrap();
+ println!("\nAnalyzing saved document:");
+ println!(" Total objects: {}", loaded.objects.len());
+
+ // Find object streams
+ let mut obj_stream_count = 0;
+ let mut compressed_count = 0;
+
+ for obj in loaded.objects.values() {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ obj_stream_count += 1;
+
+ // Count objects in stream
+ if let Ok(n) = stream.dict.get(b"N").and_then(|o| o.as_i64()) {
+ compressed_count += n as usize;
+ }
+ }
+ }
+
+ println!(" Object streams: {}", obj_stream_count);
+ println!(" Compressed objects: {}", compressed_count);
+
+ // Verify critical objects are NOT compressed
+ println!("\nVerifying critical objects:");
+
+ // Check catalog
+ if let Ok(root_ref) = loaded.trailer.get(b"Root")
+ && let Object::Reference(cat_id) = root_ref
+ {
+ check_not_compressed(&loaded, *cat_id, "Catalog");
+ }
+
+ // Check pages tree
+ if let Ok(catalog) = loaded.catalog()
+ && let Ok(pages_ref) = catalog.get(b"Pages")
+ && let Object::Reference(pages_id) = pages_ref
+ {
+ check_not_compressed(&loaded, *pages_id, "Pages tree");
+ }
+
+ // Check page objects
+ let pages = loaded.get_pages();
+ for (num, &page_id) in pages.iter() {
+ check_not_compressed(&loaded, page_id, &format!("Page {}", num));
+ }
+
+ println!("\n{}", "=".repeat(60));
+ println!("Test complete! Object streams are working correctly.");
+}
+
+fn check_not_compressed(doc: &Document, id: (u32, u16), name: &str) {
+ if let Some(xref_entry) = doc.reference_table.get(id.0) {
+ match xref_entry {
+ lopdf::xref::XrefEntry::Normal { .. } => {
+ println!(" ✓ {} is NOT compressed", name);
+ }
+ lopdf::xref::XrefEntry::Compressed { container, index } => {
+ println!(
+ " ✗ ERROR: {} is compressed in stream {} at index {}!",
+ name, container, index
+ );
+ }
+ _ => {}
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/inspect_object_stream.rs b/vendor/lopdf/examples/inspect_object_stream.rs
new file mode 100644
index 000000000..5750f03e1
--- /dev/null
+++ b/vendor/lopdf/examples/inspect_object_stream.rs
@@ -0,0 +1,135 @@
+use lopdf::{Document, Object, ObjectStream};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn main() {
+ let pdf_path = "/Users/nicolasdao/Downloads/pdfs/RFQ - SDS WebApp.docx_compressed.pdf";
+ println!("Inspecting object stream in: {}", pdf_path);
+
+ match load_document(pdf_path) {
+ Ok(doc) => {
+ // Find object stream 511
+ if let Ok(Object::Stream(stream)) = doc.get_object((511, 0)) {
+ println!("\nObject Stream 511 0 R found!");
+ println!("Dictionary: {:?}", stream.dict);
+
+ // Try to parse it
+ match ObjectStream::new(stream) {
+ Ok(obj_stream) => {
+ println!("\nSuccessfully parsed object stream!");
+ println!("Contains {} objects", obj_stream.objects.len());
+
+ // List first 20 objects
+ println!("\nFirst 20 objects in stream:");
+ for (count, ((id, generation), obj)) in obj_stream.objects.iter().enumerate() {
+ if count >= 20 {
+ break;
+ }
+ println!(" {} {} R: {:?}", id, generation, obj.type_name().unwrap_or(b"Unknown"));
+
+ // If it's a dictionary, show some keys
+ if let Object::Dictionary(dict) = obj {
+ let key_count = dict.len();
+ println!(" Dictionary with {} keys", key_count);
+ }
+ }
+
+ // Check if any page-related objects are in there
+ println!("\nChecking for page-related objects:");
+ for ((id, generation), obj) in &obj_stream.objects {
+ if let Object::Dictionary(dict) = obj {
+ if let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"Page"
+ {
+ println!(" WARNING: Page object {} {} R is in object stream!", id, generation);
+ }
+
+ // Check for font descriptors
+ if dict.has(b"FontDescriptor") || dict.has(b"BaseFont") {
+ println!(" Font-related object {} {} R", id, generation);
+ }
+ }
+ }
+ }
+ Err(e) => {
+ println!("ERROR parsing object stream: {}", e);
+ }
+ }
+ } else {
+ println!("Object stream 511 not found or not a stream!");
+ }
+
+ // Also check what critical objects might be compressed
+ println!("\n\nChecking critical object locations:");
+
+ // Check catalog
+ if let Ok(root_ref) = doc.trailer.get(b"Root")
+ && let Object::Reference(root_id) = root_ref
+ {
+ check_object_status(&doc, *root_id, "Catalog (Root)");
+ }
+
+ // Check pages tree
+ if let Ok(catalog) = doc.catalog()
+ && let Ok(pages_ref) = catalog.get(b"Pages")
+ && let Object::Reference(pages_id) = pages_ref
+ {
+ check_object_status(&doc, *pages_id, "Pages tree root");
+ }
+
+ // Check specific page objects
+ let pages = doc.get_pages();
+ for (num, &id) in pages.iter().take(2) {
+ check_object_status(&doc, id, &format!("Page {}", num));
+ }
+ }
+ Err(e) => {
+ eprintln!("Failed to load PDF: {}", e);
+ }
+ }
+}
+
+fn check_object_status(doc: &Document, id: (u32, u16), name: &str) {
+ match doc.get_object(id) {
+ Ok(_) => {
+ // Check xref entry
+ if let Some(xref_entry) = doc.reference_table.get(id.0) {
+ match xref_entry {
+ lopdf::xref::XrefEntry::Normal { offset, generation: _ } => {
+ println!("{} ({} {} R): Normal entry at offset {}", name, id.0, id.1, offset);
+ }
+ lopdf::xref::XrefEntry::Compressed { container, index } => {
+ println!(
+ "{} ({} {} R): COMPRESSED in stream {} at index {}",
+ name, id.0, id.1, container, index
+ );
+ }
+ _ => {
+ println!("{} ({} {} R): Other xref type", name, id.0, id.1);
+ }
+ }
+ } else {
+ println!("{} ({} {} R): No xref entry!", name, id.0, id.1);
+ }
+ }
+ Err(e) => {
+ println!("{} ({} {} R): ERROR - {}", name, id.0, id.1, e);
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/merge.rs b/vendor/lopdf/examples/merge.rs
new file mode 100644
index 000000000..151440c84
--- /dev/null
+++ b/vendor/lopdf/examples/merge.rs
@@ -0,0 +1,294 @@
+// if you use nightly then you can enable this feature to gain a boost in read speed of PDF's"
+//#![feature(extend_one)]
+
+#[macro_use]
+extern crate lopdf;
+
+use std::collections::BTreeMap;
+
+use lopdf::content::{Content, Operation};
+use lopdf::{Bookmark, Document, Object, ObjectId, Stream};
+
+pub fn generate_fake_document() -> Document {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Courier",
+ });
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
+ Operation::new("ET", vec![]),
+ ],
+ };
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ });
+ let pages = dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ doc
+}
+
+fn main() {
+ // Generate a stack of Documents to merge
+ // (The Bookmark layer, Document to merge)
+ let documents = vec![
+ (1u32, generate_fake_document()),
+ (2u32, generate_fake_document()),
+ (2u32, generate_fake_document()),
+ (3u32, generate_fake_document()),
+ ];
+
+ // We use this to keep track of the last Parent per layer depth.
+ let mut layer_parent: [Option<u32>; 4] = [None; 4];
+
+ // This is the last layer ran.
+ let mut last_layer = 0;
+
+ // Define a starting max_id (will be used as start index for object_ids)
+ let mut max_id = 1;
+ let mut pagenum = 1;
+ // Collect all Documents Objects grouped by a map
+ let mut documents_pages = BTreeMap::new();
+ let mut documents_objects = BTreeMap::new();
+ let mut document = Document::with_version("1.5");
+
+ // Lets try to set these to be bigger to avoid multi allocations for faster handling of files.
+ // We are just saying each Document it about 1000 objects in size. can be adjusted for better speeds.
+ // This can only be used if you use nightly or the #![feature(extend_one)] is stablized.
+ // documents_pages.extend_reserve(documents.len() * 1000);
+ // documents_objects.extend_reserve(documents.len() * 1000);
+
+ // Add a Table of Contents
+ // We set the object page to (0,0) which means it will point to the first object after it.
+ layer_parent[0] = Some(document.add_bookmark(
+ Bookmark::new("Table of Contents".to_string(), [0.0, 0.0, 0.0], 0, (0, 0)),
+ None,
+ ));
+
+ // Can set bookmark formatting and color per report bookmark added.
+ // Formating is 1 for italic 2 for bold 3 for bold and italic
+ // Color is RGB 0.0..255.0
+ for (layer, mut doc) in documents {
+ let color = [0.0, 0.0, 0.0];
+ let format = 0;
+ let mut display = String::new();
+
+ doc.renumber_objects_with(max_id);
+
+ max_id = doc.max_id + 1;
+
+ let mut first_object = None;
+
+ let pages = doc.get_pages();
+
+ // This is actually better than extend as we use less allocations and cloning then.
+ pages
+ .into_values()
+ .map(|object_id| {
+ // We use this as the return object for Bookmarking to deturmine what it points too.
+ // We only want to do this for the first page though.
+ if first_object.is_none() {
+ first_object = Some(object_id);
+ display = format!("Page {}", pagenum);
+ pagenum += 1;
+ }
+
+ (object_id, doc.get_object(object_id).unwrap().to_owned())
+ })
+ .for_each(|(key, value)| {
+ documents_pages.insert(key, value);
+ });
+
+ documents_objects.extend(doc.objects);
+
+ // Lets shadow our pointer back if nothing then set to (0,0) tto point to the next page
+ let object = first_object.unwrap_or((0, 0));
+
+ // This will use the layering to implement children under Parents in the bookmarks
+ // Example as we are generating it here.
+ // Table of Contents
+ // - Page 1
+ // -- Page 2
+ // -- Page 3
+ // --- Page 4
+
+ if layer == 0 {
+ layer_parent[0] = Some(document.add_bookmark(Bookmark::new(display, color, format, object), None));
+ last_layer = 0;
+ } else if layer == 1 {
+ layer_parent[1] =
+ Some(document.add_bookmark(Bookmark::new(display, color, format, object), layer_parent[0]));
+ last_layer = 1;
+ } else if last_layer >= layer || last_layer == layer - 1 {
+ layer_parent[layer as usize] = Some(document.add_bookmark(
+ Bookmark::new(display, color, format, object),
+ layer_parent[(layer - 1) as usize],
+ ));
+ last_layer = layer;
+ } else if last_layer > 0 {
+ layer_parent[last_layer as usize] = Some(document.add_bookmark(
+ Bookmark::new(display, color, format, object),
+ layer_parent[(last_layer - 1) as usize],
+ ));
+ } else {
+ layer_parent[1] =
+ Some(document.add_bookmark(Bookmark::new(display, color, format, object), layer_parent[0]));
+ last_layer = 1;
+ }
+ }
+
+ // Catalog and Pages are mandatory
+ let mut catalog_object: Option<(ObjectId, Object)> = None;
+ let mut pages_object: Option<(ObjectId, Object)> = None;
+
+ // Process all objects except "Page" type
+ for (object_id, object) in documents_objects.into_iter() {
+ // We have to ignore "Page" (as are processed later), "Outlines" and "Outline" objects
+ // All other objects should be collected and inserted into the main Document
+ match object.type_name().unwrap_or(b"") {
+ b"Catalog" => {
+ // Collect a first "Catalog" object and use it for the future "Pages"
+ catalog_object = Some((
+ if let Some((id, _)) = catalog_object {
+ id
+ } else {
+ object_id
+ },
+ object,
+ ));
+ }
+ b"Pages" => {
+ // Collect and update a first "Pages" object and use it for the future "Catalog"
+ // We have also to merge all dictionaries of the old and the new "Pages" object
+ if let Ok(dictionary) = object.as_dict() {
+ let mut dictionary = dictionary.clone();
+ if let Some((_, ref object)) = pages_object
+ && let Ok(old_dictionary) = object.as_dict()
+ {
+ dictionary.extend(old_dictionary);
+ }
+
+ pages_object = Some((
+ if let Some((id, _)) = pages_object {
+ id
+ } else {
+ object_id
+ },
+ Object::Dictionary(dictionary),
+ ));
+ }
+ }
+ b"Page" => {} // Ignored, processed later and separately
+ b"Outlines" => {} // Ignored, not supported yet
+ b"Outline" => {} // Ignored, not supported yet
+ _ => {
+ document.objects.insert(object_id, object);
+ }
+ }
+ }
+
+ // If no "Pages" found abort
+ if pages_object.is_none() {
+ println!("Pages root not found.");
+
+ return;
+ }
+
+ // Iter over all "Page" and collect with the parent "Pages" created before
+ for (object_id, object) in documents_pages.iter() {
+ if let Ok(dictionary) = object.as_dict() {
+ let mut dictionary = dictionary.clone();
+ dictionary.set("Parent", pages_object.as_ref().unwrap().0);
+
+ document.objects.insert(*object_id, Object::Dictionary(dictionary));
+ }
+ }
+
+ // If no "Catalog" found abort
+ if catalog_object.is_none() {
+ println!("Catalog root not found.");
+
+ return;
+ }
+
+ let (catalog_id, catalog_object) = catalog_object.unwrap();
+ let (page_id, page_object) = pages_object.unwrap();
+
+ // Build a new "Pages" with updated fields
+ if let Ok(dictionary) = page_object.as_dict() {
+ let mut dictionary = dictionary.clone();
+
+ // Set new pages count
+ dictionary.set("Count", documents_pages.len() as u32);
+
+ // Set new "Kids" list (collected from documents pages) for "Pages"
+ dictionary.set(
+ "Kids",
+ documents_pages.into_keys().map(Object::Reference).collect::<Vec<_>>(),
+ );
+
+ document.objects.insert(page_id, Object::Dictionary(dictionary));
+ }
+
+ // Build a new "Catalog" with updated fields
+ if let Ok(dictionary) = catalog_object.as_dict() {
+ let mut dictionary = dictionary.clone();
+ dictionary.set("Pages", page_id);
+ dictionary.set("PageMode", "UseOutlines");
+ dictionary.remove(b"Outlines"); // Outlines not supported in merged PDFs
+
+ document.objects.insert(catalog_id, Object::Dictionary(dictionary));
+ }
+
+ document.trailer.set("Root", catalog_id);
+
+ // Update the max internal ID as wasn't updated before due to direct objects insertion
+ document.max_id = document.objects.len() as u32;
+
+ // Reorder all new Document objects
+ document.renumber_objects();
+
+ //Set any Bookmarks to the First child if they are not set to a page
+ document.adjust_zero_pages();
+
+ //Set all bookmarks to the PDF Object tree then set the Outlines to the Bookmark content map.
+ if let Some(outline_id) = document.build_outline()
+ && let Ok(Object::Dictionary(dict)) = document.get_object_mut(catalog_id)
+ {
+ dict.set("Outlines", Object::Reference(outline_id));
+ }
+
+ // Most of the time this does nothing unless there are a lot of streams
+ // Can be disabled to speed up the process.
+ // document.compress();
+
+ // Save the merged PDF
+ // Store file in current working directory.
+ document.save("merged.pdf").unwrap();
+}
diff --git a/vendor/lopdf/examples/object_streams.rs b/vendor/lopdf/examples/object_streams.rs
new file mode 100644
index 000000000..13b87c2a9
--- /dev/null
+++ b/vendor/lopdf/examples/object_streams.rs
@@ -0,0 +1,133 @@
+use lopdf::content::{Content, Operation};
+use lopdf::dictionary;
+use lopdf::{Document, Object, SaveOptions, Stream};
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Add many objects to demonstrate object stream compression
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ });
+
+ let bold_font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica-Bold"
+ });
+
+ let italic_font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica-Oblique"
+ });
+
+ // Add some metadata objects
+ for i in 0..20 {
+ doc.add_object(dictionary! {
+ "Type" => format!("CustomData{}", i),
+ "Value" => i,
+ "Description" => format!("This is custom data object number {}", i)
+ });
+ }
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ "F2" => bold_font_id,
+ "F3" => italic_font_id,
+ },
+ });
+
+ // Create page content
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 24.into()]),
+ Operation::new("Td", vec![50.into(), 700.into()]),
+ Operation::new("Tj", vec![Object::string_literal("Object Streams Demo")]),
+ Operation::new("ET", vec![]),
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F2".into(), 16.into()]),
+ Operation::new("Td", vec![50.into(), 650.into()]),
+ Operation::new("Tj", vec![Object::string_literal("This PDF uses object streams!")]),
+ Operation::new("ET", vec![]),
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![50.into(), 600.into()]),
+ Operation::new(
+ "Tj",
+ vec![Object::string_literal(
+ "Multiple non-stream objects are compressed together.",
+ )],
+ ),
+ Operation::new("ET", vec![]),
+ ],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save with traditional format
+ let mut traditional_buffer = Vec::new();
+ doc.save_to(&mut traditional_buffer)?;
+ let traditional_size = traditional_buffer.len();
+
+ // Save with object streams
+ let mut modern_buffer = Vec::new();
+ doc.save_modern(&mut modern_buffer)?;
+ let modern_size = modern_buffer.len();
+
+ // Save with custom options
+ let mut custom_buffer = Vec::new();
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .max_objects_per_stream(10)
+ .compression_level(9)
+ .build();
+ doc.save_with_options(&mut custom_buffer, options)?;
+ let custom_size = custom_buffer.len();
+
+ // Compare sizes
+ println!("PDF Size Comparison:");
+ println!("Traditional format: {} bytes", traditional_size);
+ println!("With object streams: {} bytes", modern_size);
+ println!("With custom options: {} bytes", custom_size);
+
+ let reduction = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
+ println!("\nSize reduction: {:.1}%", reduction);
+
+ // Save the modern version to a file
+ std::fs::write("object_streams_demo.pdf", &modern_buffer)?;
+ println!("\nSaved modern PDF to: object_streams_demo.pdf");
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/print_annotations.rs b/vendor/lopdf/examples/print_annotations.rs
new file mode 100644
index 000000000..ee5b349fc
--- /dev/null
+++ b/vendor/lopdf/examples/print_annotations.rs
@@ -0,0 +1,96 @@
+// Display a summary of the annotations in a PDF file to the terminal
+//
+// Run with `cargo run --example print_annotations <pdf-file>`
+
+use core::str;
+use env_logger::Env;
+use lopdf::{Document, Object};
+use std::env;
+use std::process;
+
+fn logging() {
+ env_logger::Builder::from_env(Env::default().default_filter_or("info")).init()
+}
+
+fn args() -> Vec<String> {
+ let args: Vec<String> = env::args().collect();
+
+ if args.len() != 2 {
+ eprintln!("Usage: {} <pdf-file>", args[0]);
+ process::exit(1);
+ }
+
+ args
+}
+
+fn handle_pdf_page(doc: Document) -> u32 {
+ let mut page_counter = 1;
+
+ for page in doc.page_iter() {
+ for a in doc.get_page_annotations(page).unwrap() {
+ let subtype = a.get_deref(b"Subtype", &doc).and_then(Object::as_name).unwrap_or(b"");
+ println!(
+ "Page {}, {} annotation at {:?}",
+ page_counter,
+ str::from_utf8(subtype).unwrap(),
+ a.get_deref(b"Rect", &doc).and_then(Object::as_array).unwrap()
+ );
+ if let Ok(Object::String(c, _)) = a.get_deref(b"Contents", &doc) {
+ println!(" Contents: {:.60}", String::from_utf8_lossy(c).lines().next().unwrap());
+ }
+ if subtype == b"Link"
+ && let Ok(ahref) = a.get_deref(b"A", &doc).and_then(Object::as_dict)
+ {
+ print!(
+ " {} -> ",
+ ahref
+ .get_deref(b"S", &doc)
+ .and_then(Object::as_name)
+ .map(str::from_utf8)
+ .unwrap()
+ .unwrap()
+ );
+ if let Ok(d) = ahref.get_deref(b"D", &doc).and_then(Object::as_array) {
+ println!("{:?}", d);
+ } else if let Ok(Object::String(u, _)) = ahref.get_deref(b"URI", &doc) {
+ println!("{}", String::from_utf8_lossy(u));
+ } else if let Ok(n) = ahref
+ .get_deref(b"N", &doc)
+ .and_then(Object::as_name)
+ .map(str::from_utf8)
+ .unwrap()
+ {
+ println!("{}", n);
+ }
+ }
+ }
+ page_counter += 1;
+ }
+
+ page_counter
+}
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ logging();
+
+ let args: Vec<String> = args();
+
+ match Document::load(&args[1]) {
+ Ok(doc) => _ = handle_pdf_page(doc),
+ Err(e) => eprintln!("Error opening {:?}: {:?}", args[1], e),
+ }
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ logging();
+
+ let args: Vec<String> = args();
+
+ match Document::load(&args[1]).await {
+ Ok(doc) => _ = handle_pdf_page(doc),
+ Err(e) => eprintln!("Error opening {:?}: {:?}", args[1], e),
+ }
+}
diff --git a/vendor/lopdf/examples/replace_partial_text.rs b/vendor/lopdf/examples/replace_partial_text.rs
new file mode 100644
index 000000000..5b49d50d0
--- /dev/null
+++ b/vendor/lopdf/examples/replace_partial_text.rs
@@ -0,0 +1,170 @@
+use lopdf::{Document, Result};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn main() -> Result<()> {
+ // Load a PDF document
+ let mut doc = load_document("example.pdf")?;
+
+ println!("Loaded PDF document");
+
+ // Get all pages
+ let pages = doc.get_pages();
+ let mut total_replacements = 0;
+
+ // Example 1: Replace "Hello" with "Hi" on all pages
+ println!("\n=== Replacing 'Hello' with 'Hi' ===");
+ for page_num in pages.keys() {
+ match doc.replace_partial_text(*page_num, "Hello", "Hi", Some("?")) {
+ Ok(count) => {
+ if count > 0 {
+ println!("Page {}: Replaced {} occurrences", page_num, count);
+ total_replacements += count;
+ }
+ }
+ Err(e) => eprintln!("Error on page {}: {}", page_num, e),
+ }
+ }
+
+ // Example 2: Replace "World" with "Earth" on page 1
+ println!("\n=== Replacing 'World' with 'Earth' on page 1 ===");
+ match doc.replace_partial_text(1, "World", "Earth", None) {
+ Ok(count) => {
+ println!("Replaced {} occurrences of 'World' with 'Earth'", count);
+ total_replacements += count;
+ }
+ Err(e) => eprintln!("Error during replacement: {}", e),
+ }
+
+ // Example 3: Replace partial text in a specific pattern
+ println!("\n=== Replacing email domains ===");
+ match doc.replace_partial_text(1, "@example.com", "@company.org", Some("?")) {
+ Ok(count) => {
+ println!("Replaced {} email domains", count);
+ total_replacements += count;
+ }
+ Err(e) => eprintln!("Error during replacement: {}", e),
+ }
+
+ println!("\n=== Summary ===");
+ println!("Total replacements made: {}", total_replacements);
+
+ // Save the modified document if any replacements were made
+ if total_replacements > 0 {
+ doc.save("example_modified.pdf")?;
+ println!("Saved modified document to example_modified.pdf");
+ } else {
+ println!("No replacements were made, document not saved");
+ }
+
+ // Example 4: Demonstrating the difference between replace_text and replace_partial_text
+ println!("\n=== Comparison with original replace_text ===");
+
+ // This would fail with replace_text because it requires exact match
+ let mut doc2 = load_document("example.pdf")?;
+
+ // Original replace_text - needs exact match
+ match doc2.replace_text(1, "Hello World!", "Hi Earth!", None) {
+ Ok(_) => println!("replace_text: Successfully replaced exact text"),
+ Err(e) => println!("replace_text: Failed - {}", e),
+ }
+
+ // New replace_partial_text - can replace partial matches
+ match doc2.replace_partial_text(1, "Hello", "Hi", None) {
+ Ok(count) => println!("replace_partial_text: Replaced {} partial matches", count),
+ Err(e) => println!("replace_partial_text: Failed - {}", e),
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use lopdf::{
+ Object, Stream,
+ content::{Content, Operation},
+ dictionary,
+ };
+
+ #[test]
+ fn test_partial_replacement() -> Result<()> {
+ // Create a test document
+ let mut doc = Document::with_version("1.5");
+
+ // Create a simple page with text
+ let pages_id = doc.new_object_id();
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica",
+ });
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![100.into(), 700.into()]),
+ Operation::new("Tj", vec![Object::string_literal("Hello World! Hello Universe!")]),
+ Operation::new("ET", vec![]),
+ ],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Test partial replacement
+ let replacements = doc.replace_partial_text(1, "Hello", "Greetings", None)?;
+ assert_eq!(replacements, 2); // Should replace both occurrences
+
+ // Extract text to verify
+ let text = doc.extract_text(&[1])?;
+ assert!(text.contains("Greetings World! Greetings Universe!"));
+
+ Ok(())
+ }
+}
diff --git a/vendor/lopdf/examples/rotate.rs b/vendor/lopdf/examples/rotate.rs
new file mode 100644
index 000000000..63afecc7a
--- /dev/null
+++ b/vendor/lopdf/examples/rotate.rs
@@ -0,0 +1,63 @@
+use lopdf::Document;
+use std::str::FromStr;
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(args.len() == 4, "Not enough arguments: input_file angle output_file");
+ let input_file = &args[1];
+ let angle = i64::from_str(&args[2]).expect("error in parsing angle argument");
+ assert!(angle % 90 == 0, "angle must be a multiple of 90");
+ let output_file = &args[3];
+ let mut doc = Document::load(input_file).unwrap();
+
+ // Note: this example sets Rotate on each page individually for flexibility,
+ // but you can also set it on any node in the page tree and child pages will
+ // inherit the value.
+ for (_, page_id) in doc.get_pages() {
+ let page_dict = doc
+ .get_object_mut(page_id)
+ .and_then(|obj| obj.as_dict_mut())
+ .expect("Missing page!");
+
+ // Get the current rotation if any; the default is 0
+ let current_rotation = page_dict.get(b"Rotate").and_then(|obj| obj.as_i64()).unwrap_or(0);
+
+ // Add the angle and update
+ page_dict.set("Rotate", (current_rotation + angle) % 360);
+ }
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ // Collect command line arguments: input_file angle output_file
+ let args: Vec<String> = std::env::args().collect();
+ assert!(args.len() == 4, "Not enough arguments: input_file angle output_file");
+ let input_file = &args[1];
+ let angle = i64::from_str(&args[2]).expect("error in parsing angle argument");
+ assert!(angle % 90 == 0, "angle must be a multiple of 90");
+ let output_file = &args[3];
+ let mut doc = Document::load(input_file).await.unwrap();
+
+ // Note: this example sets Rotate on each page individually for flexibility,
+ // but you can also set it on any node in the page tree and child pages will
+ // inherit the value.
+ for (_, page_id) in doc.get_pages() {
+ let page_dict = doc
+ .get_object_mut(page_id)
+ .and_then(|obj| obj.as_dict_mut())
+ .expect("Missing page!");
+
+ // Get the current rotation if any; the default is 0
+ let current_rotation = page_dict.get(b"Rotate").and_then(|obj| obj.as_i64()).unwrap_or(0);
+
+ // Add the angle and update
+ page_dict.set("Rotate", (current_rotation + angle) % 360);
+ }
+ // Store file in current working directory.
+ doc.save(output_file).unwrap();
+}
diff --git a/vendor/lopdf/examples/test_better_compression.rs b/vendor/lopdf/examples/test_better_compression.rs
new file mode 100644
index 000000000..292500b14
--- /dev/null
+++ b/vendor/lopdf/examples/test_better_compression.rs
@@ -0,0 +1,205 @@
+use lopdf::{Document, Object, ObjectId};
+use std::collections::{HashMap, HashSet};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let pdf_path = "/Users/nicolasdao/Downloads/poor.pdf";
+
+ println!("Testing improved compression algorithm...\n");
+
+ let doc = load_document(pdf_path)?;
+
+ // Build complete reference graph
+ let (non_compressible, reason_map) = find_all_non_compressible_objects(&doc);
+
+ println!("Analysis complete:");
+ println!(" Total objects: {}", doc.objects.len());
+ println!(" Non-compressible: {}", non_compressible.len());
+ println!(" Compressible: {}", doc.objects.len() - non_compressible.len());
+
+ // Show some examples
+ println!("\nSample non-compressible objects:");
+ for (id, reason) in reason_map.iter().take(20) {
+ println!(" {} {} R: {}", id.0, id.1, reason);
+ }
+
+ // Count by reason
+ let mut reason_counts: HashMap<&str, usize> = HashMap::new();
+ for reason in reason_map.values() {
+ *reason_counts.entry(reason.as_str()).or_insert(0) += 1;
+ }
+
+ println!("\nReasons for non-compressibility:");
+ for (reason, count) in reason_counts {
+ println!(" {}: {}", reason, count);
+ }
+
+ // Simulate compression
+ let mut would_compress = Vec::new();
+ for &id in doc.objects.keys() {
+ if !non_compressible.contains(&id) {
+ would_compress.push(id);
+ }
+ }
+
+ println!("\nWould compress {} objects", would_compress.len());
+
+ // Check for orphaned references
+ let orphans = check_for_orphans(&doc, &non_compressible, &would_compress);
+
+ if orphans.is_empty() {
+ println!("\n✓ No orphaned references would be created!");
+ } else {
+ println!("\n✗ WARNING: {} orphaned references would be created:", orphans.len());
+ for (compressed_id, referencer_id) in orphans.iter().take(10) {
+ println!(
+ " {} {} R would be compressed but is referenced by {} {} R",
+ compressed_id.0, compressed_id.1, referencer_id.0, referencer_id.1
+ );
+ }
+ }
+
+ Ok(())
+}
+
+fn find_all_non_compressible_objects(doc: &Document) -> (HashSet<ObjectId>, HashMap<ObjectId, String>) {
+ let mut non_compressible = HashSet::new();
+ let mut reason_map = HashMap::new();
+
+ // Phase 1: Mark inherently non-compressible objects
+ for (&id, obj) in &doc.objects {
+ let mut reason = None;
+
+ // Streams cannot be compressed
+ if matches!(obj, Object::Stream(_)) {
+ reason = Some("Is a stream object");
+ }
+
+ // Check object type
+ if let Object::Dictionary(dict) = obj
+ && let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ {
+ match type_name {
+ b"Page" => reason = Some("Is a Page object"),
+ b"Pages" => reason = Some("Is a Pages object"),
+ b"Catalog" => reason = Some("Is a Catalog object"),
+ b"XRef" => reason = Some("Is a cross-reference stream"),
+ b"ObjStm" => reason = Some("Is an object stream"),
+ _ => {}
+ }
+ }
+
+ // Check if referenced in trailer
+ for (_key, value) in doc.trailer.iter() {
+ if value == &Object::Reference(id) {
+ reason = Some("Referenced in trailer");
+ break;
+ }
+ }
+
+ if let Some(r) = reason {
+ non_compressible.insert(id);
+ reason_map.insert(id, r.to_string());
+ }
+ }
+
+ // Phase 2: Iteratively mark objects referenced by non-compressible objects
+ let mut changed = true;
+ let mut iteration = 0;
+
+ while changed {
+ changed = false;
+ iteration += 1;
+ let mut newly_non_compressible = Vec::new();
+
+ for &nc_id in &non_compressible {
+ if let Ok(nc_obj) = doc.get_object(nc_id) {
+ let refs = collect_all_references(nc_obj);
+
+ for ref_id in refs {
+ if !non_compressible.contains(&ref_id) && doc.objects.contains_key(&ref_id) {
+ newly_non_compressible.push((
+ ref_id,
+ format!("Referenced by non-compressible {} {} R", nc_id.0, nc_id.1),
+ ));
+ changed = true;
+ }
+ }
+ }
+ }
+
+ for (id, reason) in newly_non_compressible {
+ non_compressible.insert(id);
+ reason_map.insert(id, reason);
+ }
+ }
+
+ println!("Transitive closure computed in {} iterations", iteration);
+
+ (non_compressible, reason_map)
+}
+
+fn collect_all_references(obj: &Object) -> HashSet<ObjectId> {
+ let mut refs = HashSet::new();
+
+ match obj {
+ Object::Reference(id) => {
+ refs.insert(*id);
+ }
+ Object::Array(array) => {
+ for item in array {
+ refs.extend(collect_all_references(item));
+ }
+ }
+ Object::Dictionary(dict) => {
+ for (_key, value) in dict.iter() {
+ refs.extend(collect_all_references(value));
+ }
+ }
+ Object::Stream(stream) => {
+ for (_key, value) in stream.dict.iter() {
+ refs.extend(collect_all_references(value));
+ }
+ }
+ _ => {}
+ }
+
+ refs
+}
+
+fn check_for_orphans(
+ doc: &Document, non_compressible: &HashSet<ObjectId>, would_compress: &[ObjectId],
+) -> Vec<(ObjectId, ObjectId)> {
+ let mut orphans = Vec::new();
+
+ for &nc_id in non_compressible {
+ if let Ok(nc_obj) = doc.get_object(nc_id) {
+ let refs = collect_all_references(nc_obj);
+
+ for ref_id in refs {
+ if would_compress.contains(&ref_id) {
+ orphans.push((ref_id, nc_id));
+ }
+ }
+ }
+ }
+
+ orphans
+}
diff --git a/vendor/lopdf/examples/test_decryption.rs b/vendor/lopdf/examples/test_decryption.rs
new file mode 100644
index 000000000..7ac45807a
--- /dev/null
+++ b/vendor/lopdf/examples/test_decryption.rs
@@ -0,0 +1,118 @@
+use lopdf::Document;
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ // Test loading the encrypted.pdf file
+ println!("Loading encrypted.pdf...");
+ let doc = match Document::load("assets/encrypted.pdf") {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("Failed to load encrypted.pdf: {:?}", e);
+ return;
+ }
+ };
+
+ println!("Document loaded successfully!");
+ println!("Is encrypted: {}", doc.is_encrypted());
+
+ // Try to get pages
+ let pages = doc.get_pages();
+ println!("Number of pages: {}", pages.len());
+
+ // Try to extract text
+ if !pages.is_empty() {
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ match doc.extract_text(&page_numbers) {
+ Ok(text) => {
+ println!("Text extraction successful!");
+ println!(
+ "Text preview (first 200 chars): {}",
+ text.chars().take(200).collect::<String>()
+ );
+ }
+ Err(e) => {
+ println!("Text extraction failed: {:?}", e);
+ }
+ }
+ }
+
+ // Check if we can access objects
+ println!("\nChecking object access:");
+ let max_check = 10;
+ for i in 1..=max_check {
+ if doc.get_object((i, 0)).is_ok() {
+ println!(" Object ({}, 0) found", i);
+ }
+ }
+
+ // Check trailer
+ println!("\nTrailer entries:");
+ if let Ok(root) = doc.trailer.get(b"Root") {
+ println!(" Root: {:?}", root);
+ }
+ if let Ok(encrypt) = doc.trailer.get(b"Encrypt") {
+ println!(" Encrypt: {:?}", encrypt);
+ }
+ if let Ok(info) = doc.trailer.get(b"Info") {
+ println!(" Info: {:?}", info);
+ }
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ // Test loading the encrypted.pdf file
+ println!("Loading encrypted.pdf...");
+ let doc = match Document::load("assets/encrypted.pdf").await {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("Failed to load encrypted.pdf: {:?}", e);
+ return;
+ }
+ };
+
+ println!("Document loaded successfully!");
+ println!("Is encrypted: {}", doc.is_encrypted());
+
+ // Try to get pages
+ let pages = doc.get_pages();
+ println!("Number of pages: {}", pages.len());
+
+ // Try to extract text
+ if !pages.is_empty() {
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ match doc.extract_text(&page_numbers) {
+ Ok(text) => {
+ println!("Text extraction successful!");
+ println!(
+ "Text preview (first 200 chars): {}",
+ text.chars().take(200).collect::<String>()
+ );
+ }
+ Err(e) => {
+ println!("Text extraction failed: {:?}", e);
+ }
+ }
+ }
+
+ // Check if we can access objects
+ println!("\nChecking object access:");
+ let max_check = 10;
+ for i in 1..=max_check {
+ if doc.get_object((i, 0)).is_ok() {
+ println!(" Object ({}, 0) found", i);
+ }
+ }
+
+ // Check trailer
+ println!("\nTrailer entries:");
+ if let Ok(root) = doc.trailer.get(b"Root") {
+ println!(" Root: {:?}", root);
+ }
+ if let Ok(encrypt) = doc.trailer.get(b"Encrypt") {
+ println!(" Encrypt: {:?}", encrypt);
+ }
+ if let Ok(info) = doc.trailer.get(b"Info") {
+ println!(" Info: {:?}", info);
+ }
+}
diff --git a/vendor/lopdf/examples/test_direct_objstream.rs b/vendor/lopdf/examples/test_direct_objstream.rs
new file mode 100644
index 000000000..ca044037c
--- /dev/null
+++ b/vendor/lopdf/examples/test_direct_objstream.rs
@@ -0,0 +1,84 @@
+use lopdf::{Document, Object, ObjectStream, dictionary};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Document {
+ Document::load(path).unwrap()
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Document {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await.unwrap() })
+}
+
+fn main() {
+ println!("Testing direct object stream creation and saving...\n");
+
+ // Create a simple document
+ let mut doc = Document::with_version("1.5");
+
+ // Create an object stream manually
+ let mut obj_stream = ObjectStream::builder().max_objects(10).compression_level(6).build();
+
+ // Add some objects
+ obj_stream.add_object((1, 0), Object::Integer(42)).unwrap();
+ obj_stream
+ .add_object((2, 0), Object::String(b"Test".to_vec(), lopdf::StringFormat::Literal))
+ .unwrap();
+
+ println!("Object stream has {} objects", obj_stream.object_count());
+
+ // Convert to stream object
+ let stream_obj = obj_stream.to_stream_object().unwrap();
+ println!("Stream dict: {:?}", stream_obj.dict);
+ println!("Stream has Filter: {}", stream_obj.dict.get(b"Filter").is_ok());
+
+ // Add it to the document
+ let stream_id = doc.add_object(stream_obj);
+ println!("Added object stream as {} 0 R", stream_id.0);
+
+ // Add a simple catalog
+ let pages_id = doc.add_object(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ });
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save the document
+ println!("\nSaving document...");
+ doc.save("test_direct_objstream.pdf").unwrap();
+
+ println!("Saved to test_direct_objstream.pdf");
+
+ // Load it back and check
+ println!("\nLoading back...");
+ let loaded = load_document("test_direct_objstream.pdf");
+
+ for (id, obj) in &loaded.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ println!("Found object stream {} 0 R", id.0);
+ println!(" Dict: {:?}", stream.dict);
+ println!(" Has Filter: {}", stream.dict.get(b"Filter").is_ok());
+ if let Ok(filter) = stream.dict.get(b"Filter") {
+ println!(" Filter value: {:?}", filter);
+ }
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/test_filter_roundtrip.rs b/vendor/lopdf/examples/test_filter_roundtrip.rs
new file mode 100644
index 000000000..7bc41be22
--- /dev/null
+++ b/vendor/lopdf/examples/test_filter_roundtrip.rs
@@ -0,0 +1,65 @@
+use lopdf::{Document, Object, Stream, dictionary};
+
+fn main() {
+ println!("Testing Filter round-trip...\n");
+
+ // Create a document with a compressed stream
+ let mut doc = Document::with_version("1.5");
+
+ // Create a stream with compressed content
+ let content = b"This is test content that should be compressed";
+ let mut stream = Stream::new(
+ dictionary! {
+ "Type" => "TestStream"
+ },
+ content.to_vec(),
+ );
+
+ // Compress it
+ stream.compress().unwrap();
+
+ println!("Created stream:");
+ println!(" Dictionary: {:?}", stream.dict);
+ println!(" Has Filter: {}", stream.dict.get(b"Filter").is_ok());
+ println!(" Content size: {} bytes", stream.content.len());
+
+ // Add to document
+ let stream_id = doc.add_object(stream);
+
+ // Add minimal structure
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "TestStream" => stream_id
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ // Save to bytes
+ println!("\nSaving...");
+ let mut buffer = Vec::new();
+ doc.save_to(&mut buffer).unwrap();
+
+ // Load back
+ println!("\nLoading back...");
+ let loaded = Document::load_mem(&buffer).unwrap();
+
+ // Find the stream
+ if let Ok(Object::Stream(stream)) = loaded.get_object(stream_id) {
+ println!("\nLoaded stream:");
+ println!(" Dictionary: {:?}", stream.dict);
+ println!(" Has Filter: {}", stream.dict.get(b"Filter").is_ok());
+ println!(" Content size: {} bytes", stream.content.len());
+
+ // Try to get decompressed content
+ match stream.decompressed_content() {
+ Ok(decompressed) => {
+ println!(" Decompressed successfully!");
+ println!(" Decompressed content: {:?}", String::from_utf8_lossy(&decompressed));
+ }
+ Err(e) => {
+ println!(" Failed to decompress: {}", e);
+ }
+ }
+ } else {
+ println!("ERROR: Could not find stream!");
+ }
+}
diff --git a/vendor/lopdf/examples/test_metadata.rs b/vendor/lopdf/examples/test_metadata.rs
new file mode 100644
index 000000000..1de5add1e
--- /dev/null
+++ b/vendor/lopdf/examples/test_metadata.rs
@@ -0,0 +1,33 @@
+use lopdf::Document;
+use std::env;
+
+fn main() {
+ let pdf_path = env::args().nth(1).unwrap_or_else(|| "assets/example.pdf".to_string());
+
+ let buffer = match std::fs::read(&pdf_path) {
+ Ok(buf) => buf,
+ Err(e) => {
+ eprintln!("Error reading file: {}", e);
+ std::process::exit(1);
+ }
+ };
+
+ match Document::load_metadata_mem(&buffer) {
+ Ok(metadata) => {
+ println!("PDF Version: {}", metadata.version);
+ println!("Title: {:?}", metadata.title);
+ println!("Author: {:?}", metadata.author);
+ println!("Subject: {:?}", metadata.subject);
+ println!("Keywords: {:?}", metadata.keywords);
+ println!("Creator: {:?}", metadata.creator);
+ println!("Producer: {:?}", metadata.producer);
+ println!("Creation Date: {:?}", metadata.creation_date);
+ println!("Modification Date: {:?}", metadata.modification_date);
+ println!("Page Count: {}", metadata.page_count);
+ }
+ Err(e) => {
+ eprintln!("Error: {}", e);
+ std::process::exit(1);
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/test_object_stream_creation.rs b/vendor/lopdf/examples/test_object_stream_creation.rs
new file mode 100644
index 000000000..13903355d
--- /dev/null
+++ b/vendor/lopdf/examples/test_object_stream_creation.rs
@@ -0,0 +1,126 @@
+use lopdf::{Dictionary, Document, Object, SaveOptions};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Create a simple PDF with objects that can be compressed
+ let mut doc = Document::with_version("1.4");
+
+ // Create catalog
+ let mut catalog = Dictionary::new();
+ catalog.set("Type", "Catalog");
+ catalog.set("Pages", Object::Reference((2, 0)));
+ doc.objects.insert((1, 0), Object::Dictionary(catalog));
+
+ // Create pages root
+ let mut pages = Dictionary::new();
+ pages.set("Type", "Pages");
+ pages.set("Kids", vec![Object::Reference((3, 0))]);
+ pages.set("Count", 1);
+ doc.objects.insert((2, 0), Object::Dictionary(pages));
+
+ // Create a page
+ let mut page = Dictionary::new();
+ page.set("Type", "Page");
+ page.set("Parent", Object::Reference((2, 0)));
+ page.set("MediaBox", vec![0.into(), 0.into(), 612.into(), 792.into()]);
+ doc.objects.insert((3, 0), Object::Dictionary(page));
+
+ // Create some metadata objects that should be compressible
+ for i in 10..20 {
+ let mut meta = Dictionary::new();
+ meta.set("Type", "Metadata");
+ meta.set("ID", i);
+ meta.set("Data", format!("This is metadata object {}", i));
+ doc.objects.insert((i as u32, 0), Object::Dictionary(meta));
+ }
+
+ // Create some annotation objects that should be compressible
+ for i in 20..30 {
+ let mut annot = Dictionary::new();
+ annot.set("Type", "Annot");
+ annot.set("Subtype", "Text");
+ annot.set("Contents", format!("Annotation {}", i));
+ annot.set("Rect", vec![100.into(), 100.into(), 200.into(), 200.into()]);
+ doc.objects.insert((i as u32, 0), Object::Dictionary(annot));
+ }
+
+ // Set up trailer
+ doc.trailer.set("Root", Object::Reference((1, 0)));
+ doc.max_id = 30;
+ doc.renumber_objects();
+
+ // Save without object streams
+ println!("Saving without object streams...");
+ doc.save("test_no_objstm.pdf")?;
+
+ // Save with object streams
+ println!("Saving with object streams...");
+ let options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true,
+ ..Default::default()
+ };
+ doc.save_with_options(&mut std::fs::File::create("test_with_objstm.pdf")?, options)?;
+
+ // Check file sizes
+ let no_objstm_size = std::fs::metadata("test_no_objstm.pdf")?.len();
+ let with_objstm_size = std::fs::metadata("test_with_objstm.pdf")?.len();
+
+ println!("\nFile sizes:");
+ println!(" Without object streams: {} bytes", no_objstm_size);
+ println!(" With object streams: {} bytes", with_objstm_size);
+ println!(
+ " Reduction: {:.1}%",
+ (1.0 - with_objstm_size as f64 / no_objstm_size as f64) * 100.0
+ );
+
+ // Load the compressed PDF and check for object streams
+ println!("\nChecking compressed PDF...");
+ let compressed_doc = load_document("test_with_objstm.pdf")?;
+
+ let mut objstm_count = 0;
+ let mut compressed_count = 0;
+
+ for obj in compressed_doc.objects.values() {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ objstm_count += 1;
+ // Count objects in this stream
+ if let Ok(n) = stream.dict.get(b"N")
+ && let Ok(n_val) = n.as_i64()
+ {
+ compressed_count += n_val as usize;
+ }
+ }
+ }
+
+ println!(" Object streams found: {}", objstm_count);
+ println!(" Total compressed objects: {}", compressed_count);
+
+ // Also check the raw file content
+ println!("\nChecking raw file for /ObjStm...");
+ let content = std::fs::read_to_string("test_with_objstm.pdf").unwrap_or_default();
+ let objstm_occurrences = content.matches("/ObjStm").count();
+ println!(" /ObjStm occurrences in file: {}", objstm_occurrences);
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/test_object_stream_roundtrip.rs b/vendor/lopdf/examples/test_object_stream_roundtrip.rs
new file mode 100644
index 000000000..68f41d3d5
--- /dev/null
+++ b/vendor/lopdf/examples/test_object_stream_roundtrip.rs
@@ -0,0 +1,124 @@
+use lopdf::{Document, SaveOptions};
+use std::fs::File;
+use std::io::Write;
+
+fn main() {
+ println!("Testing object stream round-trip...\n");
+
+ // First, create a simple PDF with object streams
+ let mut doc = Document::with_version("1.5");
+
+ // Add a simple page
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+
+ // Page content
+ doc.objects.insert(
+ content_id,
+ lopdf::Stream::new(
+ lopdf::dictionary! {},
+ b"BT /F1 12 Tf 100 700 Td (Hello World) Tj ET".to_vec(),
+ )
+ .into(),
+ );
+
+ // Font
+ doc.objects.insert(
+ font_id,
+ lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ }
+ .into(),
+ );
+
+ // Page
+ doc.objects.insert(
+ page_id,
+ lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => content_id,
+ "Resources" => lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => font_id
+ }
+ }
+ }
+ .into(),
+ );
+
+ // Pages
+ doc.objects.insert(
+ pages_id,
+ lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1
+ }
+ .into(),
+ );
+
+ // Catalog
+ let catalog_id = doc.add_object(lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save with object streams
+ println!("Saving original PDF with object streams...");
+ let options = SaveOptions {
+ use_object_streams: true,
+ ..Default::default()
+ };
+
+ let mut original_bytes = Vec::new();
+ doc.save_with_options(&mut original_bytes, options.clone()).unwrap();
+ println!("Original size: {} bytes", original_bytes.len());
+
+ // Write to file for inspection
+ let mut file = File::create("test_roundtrip_original.pdf").unwrap();
+ file.write_all(&original_bytes).unwrap();
+
+ // Now load it back
+ println!("\nLoading PDF back...");
+ let mut loaded_doc = Document::load_mem(&original_bytes).unwrap();
+ println!("Loaded {} objects", loaded_doc.objects.len());
+
+ // Check for object streams
+ let mut obj_stream_count = 0;
+ for (id, obj) in &loaded_doc.objects {
+ if let lopdf::Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ obj_stream_count += 1;
+ println!("Found object stream {} 0 R", id.0);
+ if let Ok(filter) = stream.dict.get(b"Filter") {
+ println!(" Has Filter: {:?}", filter);
+ } else {
+ println!(" WARNING: No Filter!");
+ }
+ }
+ }
+ println!("Total object streams found: {}", obj_stream_count);
+
+ // Save again with object streams
+ println!("\nSaving loaded PDF with object streams again...");
+ let mut resaved_bytes = Vec::new();
+ loaded_doc.save_with_options(&mut resaved_bytes, options).unwrap();
+ println!("Resaved size: {} bytes", resaved_bytes.len());
+
+ // Write to file for inspection
+ let mut file = File::create("test_roundtrip_resaved.pdf").unwrap();
+ file.write_all(&resaved_bytes).unwrap();
+
+ println!("\nDone! Check test_roundtrip_original.pdf and test_roundtrip_resaved.pdf");
+}
diff --git a/vendor/lopdf/examples/test_real_pdf_compression_with_fix.rs b/vendor/lopdf/examples/test_real_pdf_compression_with_fix.rs
new file mode 100644
index 000000000..184a31648
--- /dev/null
+++ b/vendor/lopdf/examples/test_real_pdf_compression_with_fix.rs
@@ -0,0 +1,92 @@
+use lopdf::{Document, SaveOptions};
+use std::path::Path;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Test with the PDF from the Downloads folder
+ let pdf_path = "/Users/nicolasdao/Downloads/pdfs/pdf-demo.pdf";
+
+ if !Path::new(pdf_path).exists() {
+ eprintln!("Test PDF not found at: {}", pdf_path);
+ return Ok(());
+ }
+
+ println!("Testing object stream compression with real PDF...");
+ println!("Input: {}", pdf_path);
+
+ // Load the PDF
+ let mut doc = load_document(pdf_path)?;
+
+ // Save without object streams
+ let mut normal_output = Vec::new();
+ doc.save_to(&mut normal_output)?;
+
+ // Save with object streams
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .build();
+
+ let mut compressed_output = Vec::new();
+ doc.save_with_options(&mut compressed_output, options)?;
+
+ // Calculate results
+ let original_size = std::fs::metadata(pdf_path)?.len();
+ let normal_size = normal_output.len();
+ let compressed_size = compressed_output.len();
+
+ println!("\nFile sizes:");
+ println!(" Original file: {} bytes", original_size);
+ println!(" After re-save (no compression): {} bytes", normal_size);
+ println!(" With object streams: {} bytes", compressed_size);
+
+ let reduction_from_original = (1.0 - (compressed_size as f64 / original_size as f64)) * 100.0;
+ let reduction_from_resave = (1.0 - (compressed_size as f64 / normal_size as f64)) * 100.0;
+
+ println!("\nSize reduction:");
+ println!(" From original: {:.1}%", reduction_from_original);
+ println!(" From re-saved: {:.1}%", reduction_from_resave);
+
+ // Check compression details
+ let content = String::from_utf8_lossy(&compressed_output);
+ let objstm_count = content.matches("/ObjStm").count();
+
+ println!("\nCompression details:");
+ println!(" Object streams created: {}", objstm_count);
+
+ // Count how many objects are in the PDF
+ let total_objects = doc.objects.len();
+ println!(" Total objects in PDF: {}", total_objects);
+
+ // Save to file for manual inspection
+ let output_path = "/Users/nicolasdao/Downloads/pdfs/pdf-demo_fixed_compression.pdf";
+ std::fs::write(output_path, &compressed_output)?;
+ println!("\nCompressed PDF saved to: {}", output_path);
+
+ if reduction_from_original > 20.0 {
+ println!("\n✅ SUCCESS: Achieved {:.1}% size reduction!", reduction_from_original);
+ } else {
+ println!(
+ "\n⚠️ Size reduction is {:.1}% (expected 26-38%)",
+ reduction_from_original
+ );
+ }
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/test_structural_compression.rs b/vendor/lopdf/examples/test_structural_compression.rs
new file mode 100644
index 000000000..af0c347bb
--- /dev/null
+++ b/vendor/lopdf/examples/test_structural_compression.rs
@@ -0,0 +1,143 @@
+use lopdf::{Document, Object, SaveOptions, dictionary};
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ println!("Testing structural object compression...\n");
+
+ // Create a simple PDF with structural objects
+ let mut doc = Document::with_version("1.4");
+
+ // Create catalog (should be compressed)
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ });
+
+ // Create pages tree (should be compressed)
+ let _pages_id = doc.add_object(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference((3, 0))],
+ "Count" => 1
+ });
+
+ // Create page (should be compressed)
+ let _page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Resources" => dictionary! {}
+ });
+
+ // Add some font objects for good measure
+ for i in 10..15 {
+ doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => format!("Font{}", i)
+ });
+ }
+
+ // Set up trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.max_id = 15;
+ doc.renumber_objects();
+
+ // Save without object streams
+ println!("Saving without object streams...");
+ let mut no_objstm = Vec::new();
+ doc.save_to(&mut no_objstm)?;
+
+ // Save with object streams
+ println!("Saving with object streams...");
+ let mut with_objstm = Vec::new();
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .max_objects_per_stream(100)
+ .compression_level(6)
+ .build();
+ doc.save_with_options(&mut with_objstm, options)?;
+
+ // Analyze results
+ let no_objstm_str = String::from_utf8_lossy(&no_objstm);
+ let with_objstm_str = String::from_utf8_lossy(&with_objstm);
+
+ println!("\n=== Analysis ===");
+ println!("Without object streams: {} bytes", no_objstm.len());
+ println!("With object streams: {} bytes", with_objstm.len());
+ println!(
+ "Size reduction: {:.1}%",
+ (1.0 - with_objstm.len() as f64 / no_objstm.len() as f64) * 100.0
+ );
+
+ // Check for object stream markers
+ let objstm_count = with_objstm_str.matches("/ObjStm").count();
+ println!("\nObject streams created: {}", objstm_count);
+
+ // Check that individual objects are NOT present in compressed version
+ println!("\n=== Checking for individual object definitions ===");
+
+ // These patterns should NOT appear in the compressed version
+ let patterns = vec![
+ "1 0 obj", // Catalog
+ "2 0 obj", // Pages
+ "3 0 obj", // Page
+ "10 0 obj", // Font
+ "11 0 obj", // Font
+ ];
+
+ for pattern in patterns {
+ let in_original = no_objstm_str.contains(pattern);
+ let in_compressed = with_objstm_str.contains(pattern);
+
+ println!("{}: original={}, compressed={}", pattern, in_original, in_compressed);
+
+ if in_compressed {
+ println!(" WARNING: Object {} should have been compressed!", pattern);
+ }
+ }
+
+ // Save to files for manual inspection
+ std::fs::write("test_no_objstm.pdf", &no_objstm)?;
+ std::fs::write("test_with_objstm.pdf", &with_objstm)?;
+
+ println!("\nSaved test files:");
+ println!(" - test_no_objstm.pdf");
+ println!(" - test_with_objstm.pdf");
+
+ // Load and verify the compressed PDF
+ println!("\n=== Verifying compressed PDF ===");
+ let compressed_doc = Document::load_mem(&with_objstm[..])?;
+
+ let mut objstm_found = 0;
+ let mut compressed_objects = 0;
+
+ for obj in compressed_doc.objects.values() {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ objstm_found += 1;
+
+ // Count objects in this stream
+ if let Ok(n) = stream.dict.get(b"N")
+ && let Ok(n_val) = n.as_i64()
+ {
+ compressed_objects += n_val as usize;
+ println!("Object stream found with {} objects", n_val);
+ }
+ }
+ }
+
+ println!("\nTotal object streams: {}", objstm_found);
+ println!("Total compressed objects: {}", compressed_objects);
+
+ if compressed_objects < 5 {
+ println!("\nERROR: Expected at least 5 objects to be compressed (Catalog, Pages, Page, and Fonts)");
+ println!("Only {} objects were compressed!", compressed_objects);
+ } else {
+ println!("\n✓ SUCCESS: Structural objects are being compressed!");
+ }
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/verify_decryption.rs b/vendor/lopdf/examples/verify_decryption.rs
new file mode 100644
index 000000000..ded352af4
--- /dev/null
+++ b/vendor/lopdf/examples/verify_decryption.rs
@@ -0,0 +1,245 @@
+// Example demonstrating PDF decryption capabilities
+// This verifies the modifications to src/reader.rs for handling encrypted PDFs
+
+use lopdf::{Document, EncryptionState, EncryptionVersion, Permissions};
+
+#[cfg(not(feature = "async"))]
+fn main() {
+ println!("=== PDF Decryption Verification ===\n");
+
+ // Test 1: Load an encrypted PDF from assets
+ println!("Test 1: Loading encrypted PDF from assets/encrypted.pdf");
+ match Document::load("assets/encrypted.pdf") {
+ Ok(doc) => {
+ println!("✓ Successfully loaded encrypted PDF");
+ println!(" - Is encrypted: {}", doc.is_encrypted());
+ println!(" - Number of pages: {}", doc.get_pages().len());
+ println!(" - Has encryption state: {}", doc.encryption_state.is_some());
+
+ // Try to extract text
+ let pages = doc.get_pages();
+ let page_nums: Vec<u32> = pages.keys().cloned().collect();
+ match doc.extract_text(&page_nums) {
+ Ok(text) => {
+ println!(" - Text extraction successful");
+ println!(" - Text length: {} characters", text.len());
+ }
+ Err(e) => println!(" - Text extraction failed: {:?}", e),
+ }
+ }
+ Err(e) => println!("✗ Failed to load encrypted PDF: {:?}", e),
+ }
+
+ println!();
+
+ // Test 2: Create and encrypt a new PDF, then verify it can be loaded
+ println!("Test 2: Creating, encrypting, and re-loading a PDF");
+
+ // Create a simple PDF
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID (required for encryption)
+ doc.trailer.set(
+ "ID",
+ lopdf::Object::Array(vec![
+ lopdf::Object::String(vec![1u8; 16], lopdf::StringFormat::Literal),
+ lopdf::Object::String(vec![2u8; 16], lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Add minimal structure
+ let catalog = doc.add_object(lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ });
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog));
+
+ doc.objects.insert(
+ (2, 0),
+ lopdf::Object::Dictionary(lopdf::dictionary! {
+ "Type" => "Pages",
+ "Count" => 0,
+ "Kids" => Vec::<lopdf::Object>::new()
+ }),
+ );
+
+ // Encrypt the document
+ let encryption_version = EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "",
+ user_password: "",
+ key_length: 128,
+ permissions: Permissions::all(),
+ };
+
+ match EncryptionState::try_from(encryption_version) {
+ Ok(state) => {
+ doc.encrypt(&state).unwrap();
+ println!("✓ Document encrypted successfully");
+
+ // Save to temporary location
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_encrypted.pdf");
+ doc.save(&path).unwrap();
+ println!("✓ Encrypted document saved");
+
+ // Try to load it back
+ match Document::load(&path) {
+ Ok(loaded_doc) => {
+ println!("✓ Encrypted document re-loaded successfully");
+ println!(" - Is encrypted: {}", loaded_doc.is_encrypted());
+ println!(" - Has encryption state: {}", loaded_doc.encryption_state.is_some());
+ }
+ Err(e) => println!("✗ Failed to re-load encrypted document: {:?}", e),
+ }
+ }
+ Err(e) => println!("✗ Failed to create encryption state: {:?}", e),
+ }
+
+ println!();
+
+ // Test 3: Verify object access in encrypted PDF
+ println!("Test 3: Verifying object access in encrypted PDF");
+ if let Ok(doc) = Document::load("assets/encrypted.pdf") {
+ let mut accessible_objects = 0;
+ let mut total_checked = 0;
+
+ for i in 1..=20 {
+ total_checked += 1;
+ if doc.get_object((i, 0)).is_ok() {
+ accessible_objects += 1;
+ }
+ }
+
+ println!("✓ Object access test completed");
+ println!(" - Objects checked: {}", total_checked);
+ println!(" - Objects accessible: {}", accessible_objects);
+ println!(
+ " - Success rate: {:.1}%",
+ (accessible_objects as f64 / total_checked as f64) * 100.0
+ );
+ }
+
+ println!("\n=== All decryption tests completed ===");
+}
+
+#[cfg(feature = "async")]
+#[tokio::main]
+async fn main() {
+ println!("=== PDF Decryption Verification (Async) ===\n");
+
+ // Test 1: Load an encrypted PDF from assets
+ println!("Test 1: Loading encrypted PDF from assets/encrypted.pdf");
+ match Document::load("assets/encrypted.pdf").await {
+ Ok(doc) => {
+ println!("✓ Successfully loaded encrypted PDF");
+ println!(" - Is encrypted: {}", doc.is_encrypted());
+ println!(" - Number of pages: {}", doc.get_pages().len());
+ println!(" - Has encryption state: {}", doc.encryption_state.is_some());
+
+ // Try to extract text
+ let pages = doc.get_pages();
+ let page_nums: Vec<u32> = pages.keys().cloned().collect();
+ match doc.extract_text(&page_nums) {
+ Ok(text) => {
+ println!(" - Text extraction successful");
+ println!(" - Text length: {} characters", text.len());
+ }
+ Err(e) => println!(" - Text extraction failed: {:?}", e),
+ }
+ }
+ Err(e) => println!("✗ Failed to load encrypted PDF: {:?}", e),
+ }
+
+ println!();
+
+ // Test 2: Create and encrypt a new PDF, then verify it can be loaded
+ println!("Test 2: Creating, encrypting, and re-loading a PDF");
+
+ // Create a simple PDF
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID (required for encryption)
+ doc.trailer.set(
+ "ID",
+ lopdf::Object::Array(vec![
+ lopdf::Object::String(vec![1u8; 16], lopdf::StringFormat::Literal),
+ lopdf::Object::String(vec![2u8; 16], lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Add minimal structure
+ let catalog = doc.add_object(lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ });
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog));
+
+ doc.objects.insert(
+ (2, 0),
+ lopdf::Object::Dictionary(lopdf::dictionary! {
+ "Type" => "Pages",
+ "Count" => 0,
+ "Kids" => Vec::<lopdf::Object>::new()
+ }),
+ );
+
+ // Encrypt the document
+ let encryption_version = EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "",
+ user_password: "",
+ key_length: 128,
+ permissions: Permissions::all(),
+ };
+
+ match EncryptionState::try_from(encryption_version) {
+ Ok(state) => {
+ doc.encrypt(&state).unwrap();
+ println!("✓ Document encrypted successfully");
+
+ // Save to temporary location
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_encrypted.pdf");
+ doc.save(&path).unwrap();
+ println!("✓ Encrypted document saved");
+
+ // Try to load it back
+ match Document::load(&path).await {
+ Ok(loaded_doc) => {
+ println!("✓ Encrypted document re-loaded successfully");
+ println!(" - Is encrypted: {}", loaded_doc.is_encrypted());
+ println!(" - Has encryption state: {}", loaded_doc.encryption_state.is_some());
+ }
+ Err(e) => println!("✗ Failed to re-load encrypted document: {:?}", e),
+ }
+ }
+ Err(e) => println!("✗ Failed to create encryption state: {:?}", e),
+ }
+
+ println!();
+
+ // Test 3: Verify object access in encrypted PDF
+ println!("Test 3: Verifying object access in encrypted PDF");
+ if let Ok(doc) = Document::load("assets/encrypted.pdf").await {
+ let mut accessible_objects = 0;
+ let mut total_checked = 0;
+
+ for i in 1..=20 {
+ total_checked += 1;
+ if doc.get_object((i, 0)).is_ok() {
+ accessible_objects += 1;
+ }
+ }
+
+ println!("✓ Object access test completed");
+ println!(" - Objects checked: {}", total_checked);
+ println!(" - Objects accessible: {}", accessible_objects);
+ println!(
+ " - Success rate: {:.1}%",
+ (accessible_objects as f64 / total_checked as f64) * 100.0
+ );
+ }
+
+ println!("\n=== All decryption tests completed ===");
+}
diff --git a/vendor/lopdf/examples/verify_page_compression.rs b/vendor/lopdf/examples/verify_page_compression.rs
new file mode 100644
index 000000000..9aa40341d
--- /dev/null
+++ b/vendor/lopdf/examples/verify_page_compression.rs
@@ -0,0 +1,95 @@
+use lopdf::{Document, Object};
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Document::load(path)?)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
+ Ok(Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })?)
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let compressed_path = "/Users/nicolasdao/Downloads/pdfs/pdf-demo_compressed.pdf";
+
+ println!("Checking if Page objects are in object streams...\n");
+
+ // Load the compressed PDF
+ let doc = load_document(compressed_path)?;
+
+ // Check for object streams
+ let mut objstm_count = 0;
+ let mut total_compressed = 0;
+
+ for (id, obj) in &doc.objects {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ objstm_count += 1;
+
+ // Get number of objects in this stream
+ if let Ok(n) = stream.dict.get(b"N")
+ && let Ok(n_val) = n.as_i64()
+ {
+ total_compressed += n_val;
+ println!("Object stream {} 0 R contains {} objects", id.0, n_val);
+ }
+ }
+ }
+
+ println!("\nTotal object streams: {}", objstm_count);
+ println!("Total compressed objects: {}", total_compressed);
+
+ // Check if we can find Page objects as top-level objects
+ let mut page_count = 0;
+ let mut pages_count = 0;
+ let mut catalog_count = 0;
+
+ for obj in doc.objects.values() {
+ if let Object::Dictionary(dict) = obj
+ && let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ {
+ match type_name {
+ b"Page" => page_count += 1,
+ b"Pages" => pages_count += 1,
+ b"Catalog" => catalog_count += 1,
+ _ => {}
+ }
+ }
+ }
+
+ println!("\nTop-level objects found:");
+ println!(" Page objects: {}", page_count);
+ println!(" Pages objects: {}", pages_count);
+ println!(" Catalog objects: {}", catalog_count);
+
+ if page_count == 0 && pages_count == 0 {
+ println!("\n✓ SUCCESS: Page and Pages objects are compressed into object streams!");
+ } else {
+ println!("\n✗ WARNING: Some structural objects may not be compressed");
+ }
+
+ // Check the raw PDF content
+ let content = std::fs::read_to_string(compressed_path)?;
+
+ // Look for individual page definitions
+ let page_defs = content.matches(" 0 obj\n<</Type/Page").count();
+ println!("\nPage definitions found in raw PDF: {}", page_defs);
+
+ if page_defs == 0 {
+ println!("✓ No individual Page object definitions found - they're in object streams!");
+ }
+
+ Ok(())
+}
diff --git a/vendor/lopdf/examples/verify_pdf.rs b/vendor/lopdf/examples/verify_pdf.rs
new file mode 100644
index 000000000..01d5644c9
--- /dev/null
+++ b/vendor/lopdf/examples/verify_pdf.rs
@@ -0,0 +1,64 @@
+use lopdf::{Document, Object};
+use std::env;
+
+#[cfg(feature = "async")]
+use tokio::runtime::Builder;
+
+#[cfg(not(feature = "async"))]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Document::load(path)
+}
+
+#[cfg(feature = "async")]
+fn load_document(path: &str) -> Result<Document, lopdf::Error> {
+ Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move { Document::load(path).await })
+}
+
+fn main() {
+ let args: Vec<String> = env::args().collect();
+ if args.len() < 2 {
+ eprintln!("Usage: {} <pdf_file>", args[0]);
+ std::process::exit(1);
+ }
+
+ let pdf_path = &args[1];
+ println!("Verifying PDF: {}", pdf_path);
+
+ match load_document(pdf_path) {
+ Ok(doc) => {
+ println!("✓ PDF loaded successfully");
+ println!(" Version: {:?}", doc.version);
+ println!(" Objects: {}", doc.objects.len());
+
+ // Count pages
+ let pages = doc.get_pages();
+ println!(" Pages: {}", pages.len());
+
+ // Check for object streams
+ let mut obj_stream_count = 0;
+ for obj in doc.objects.values() {
+ if let Object::Stream(stream) = obj
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ obj_stream_count += 1;
+ }
+ }
+
+ if obj_stream_count > 0 {
+ println!(" Object streams: {}", obj_stream_count);
+ }
+
+ println!("\nPDF is valid and can be opened!");
+ }
+ Err(e) => {
+ eprintln!("✗ Failed to load PDF: {}", e);
+ std::process::exit(1);
+ }
+ }
+}
diff --git a/vendor/lopdf/examples/verify_trailer_compression_fix.rs b/vendor/lopdf/examples/verify_trailer_compression_fix.rs
new file mode 100644
index 000000000..cda7a1c67
--- /dev/null
+++ b/vendor/lopdf/examples/verify_trailer_compression_fix.rs
@@ -0,0 +1,90 @@
+use lopdf::{Document, Object, ObjectStream, SaveOptions, dictionary};
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ println!("Verifying trailer-referenced object compression fix...\n");
+
+ // Create a simple PDF with catalog and info
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Test PDF",
+ "Author" => "lopdf",
+ "Creator" => "lopdf test",
+ "Producer" => "lopdf",
+ "CreationDate" => "D:20250807120000Z",
+ });
+
+ // Set in trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+
+ // Test compression eligibility
+ println!("Testing compression eligibility after trailer references:");
+
+ let catalog_obj = doc.objects.get(&catalog_id).unwrap();
+ let can_compress_catalog = ObjectStream::can_be_compressed(catalog_id, catalog_obj, &doc);
+ println!(" Catalog (Root): can_be_compressed = {}", can_compress_catalog);
+
+ let info_obj = doc.objects.get(&info_id).unwrap();
+ let can_compress_info = ObjectStream::can_be_compressed(info_id, info_obj, &doc);
+ println!(" Info dictionary: can_be_compressed = {}", can_compress_info);
+
+ // Save with and without object streams
+ let mut normal_output = Vec::new();
+ doc.save_to(&mut normal_output)?;
+
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .build();
+
+ let mut compressed_output = Vec::new();
+ doc.save_with_options(&mut compressed_output, options)?;
+
+ println!("\nFile sizes:");
+ println!(" Without object streams: {} bytes", normal_output.len());
+ println!(" With object streams: {} bytes", compressed_output.len());
+
+ let reduction_pct = (1.0 - (compressed_output.len() as f64 / normal_output.len() as f64)) * 100.0;
+ println!(" Size reduction: {:.1}%", reduction_pct);
+
+ // Check if catalog is in object stream
+ let content = String::from_utf8_lossy(&compressed_output);
+ let has_objstm = content.contains("/ObjStm");
+ let catalog_as_individual = content.contains(&format!("{} 0 obj\n<</Type/Catalog", catalog_id.0));
+ let info_as_individual = content.contains(&format!("{} 0 obj\n<</Title", info_id.0));
+
+ println!("\nCompression results:");
+ println!(" Has object streams: {}", has_objstm);
+ println!(" Catalog as individual object: {}", catalog_as_individual);
+ println!(" Info as individual object: {}", info_as_individual);
+
+ if can_compress_catalog && can_compress_info && has_objstm && !catalog_as_individual && !info_as_individual {
+ println!("\n✅ SUCCESS: Trailer-referenced objects are properly compressed!");
+ } else {
+ println!("\n❌ FAILURE: Fix not working correctly");
+ }
+
+ Ok(())
+}
diff --git a/vendor/lopdf/rustfmt.toml b/vendor/lopdf/rustfmt.toml
new file mode 100644
index 000000000..11b4ac63e
--- /dev/null
+++ b/vendor/lopdf/rustfmt.toml
@@ -0,0 +1,6 @@
+format_strings = false
+reorder_imports = true
+fn_params_layout = "Compressed"
+max_width = 120
+comment_width = 120
+wrap_comments = true
diff --git a/vendor/lopdf/src/bookmarks.rs b/vendor/lopdf/src/bookmarks.rs
new file mode 100644
index 000000000..ea19fad3e
--- /dev/null
+++ b/vendor/lopdf/src/bookmarks.rs
@@ -0,0 +1,156 @@
+use super::{Dictionary, Document, Object, ObjectId};
+use std::collections::HashMap;
+
+#[derive(Debug, Clone)]
+pub struct Bookmark {
+ /// Children, Must be a Collection that allows for insertion of the same page ID.
+ pub children: Vec<u32>,
+ pub title: String,
+ /// 0, 1 for italic, 2 for bold, 3 for italic bold
+ pub format: u32,
+ /// R,G,B
+ pub color: [f32; 3],
+ pub page: ObjectId,
+ pub id: u32,
+}
+
+impl Bookmark {
+ pub fn new(title: String, color: [f32; 3], format: u32, page: ObjectId) -> Bookmark {
+ Bookmark {
+ children: Vec::new(),
+ title,
+ format,
+ color,
+ page,
+ id: 0,
+ }
+ }
+}
+
+impl Document {
+ pub fn add_bookmark(&mut self, mut bookmark: Bookmark, parent: Option<u32>) -> u32 {
+ self.max_bookmark_id += 1;
+ let id = self.max_bookmark_id;
+
+ bookmark.id = id;
+
+ if let Some(p) = parent {
+ if let Some(b) = self.bookmark_table.get_mut(&p) {
+ b.children.push(id);
+ }
+ } else {
+ self.bookmarks.push(id);
+ }
+
+ self.bookmark_table.insert(id, bookmark);
+ id
+ }
+
+ fn outline_child(
+ &self, maxid: &mut u32, parent: (ObjectId, &[u32]), processed: &mut HashMap<ObjectId, Dictionary>,
+ ) -> (Option<ObjectId>, Option<ObjectId>, i64) {
+ let mut first: Option<ObjectId> = None;
+ let mut last: Option<ObjectId> = None;
+ let count = parent.1.len();
+ for i in parent.1 {
+ let mut child = Dictionary::new();
+ *maxid += 1;
+ let id: ObjectId = (*maxid, 0);
+ *maxid += 1;
+ let info_id: ObjectId = (*maxid, 0);
+ let bookmark = self.bookmark_table.get(i).unwrap();
+
+ let info = dictionary! {
+ "D" => vec![bookmark.page.into(), Object::Name("Fit".into())],
+ "S" => "GoTo",
+ };
+
+ let title_bytes = if bookmark.title.is_ascii() {
+ bookmark.title.as_bytes().to_vec()
+ } else {
+ // If the title contains non-ASCII characters:
+ // Create a new vector with the UTF-16 Byte Order Mark (BOM) for UTF-16BE.
+ let mut bom = vec![0xFE, 0xFF];
+ let utf16_title = bookmark.title.encode_utf16();
+ // Append the UTF-16BE encoded bytes of the title to the BOM.
+ bom.extend(utf16_title.flat_map(u16::to_be_bytes));
+ bom
+ };
+
+ child.set("Parent", parent.0);
+ child.set("Title", Object::string_literal(title_bytes));
+ child.set("A", info_id);
+ child.set("F", Object::Integer(bookmark.format.into()));
+ child.set(
+ "C",
+ vec![
+ bookmark.color[0].into(),
+ bookmark.color[1].into(),
+ bookmark.color[2].into(),
+ ],
+ );
+
+ if first.is_none() {
+ first = Some(id);
+ } else if let Some(x) = last {
+ let inner_object = processed.get_mut(&x).unwrap();
+ inner_object.set("Next", id);
+ child.set("Prev", x);
+ }
+
+ last = Some(id);
+
+ if !bookmark.children.is_empty() {
+ let (c_first, c_last, c_count) = self.outline_child(maxid, (id, &bookmark.children[..]), processed);
+
+ if let Some(n) = c_first {
+ child.set("First", n);
+ }
+
+ if let Some(n) = c_last {
+ child.set("Last", n);
+ }
+
+ child.set("Count", c_count);
+ }
+
+ processed.insert(id, child);
+ processed.insert(info_id, info);
+ }
+
+ (first, last, count as i64)
+ }
+
+ pub fn build_outline(&mut self) -> Option<ObjectId> {
+ let mut processed: HashMap<ObjectId, Dictionary> = HashMap::new();
+
+ if !self.bookmarks.is_empty() {
+ let mut outline = Dictionary::new();
+ let mut maxid = self.max_id;
+ maxid += 1;
+ let id: ObjectId = (maxid, 0);
+
+ let (first, last, count) = self.outline_child(&mut maxid, (id, &self.bookmarks[..]), &mut processed);
+
+ if let Some(n) = first {
+ outline.set("First", n);
+ }
+
+ if let Some(n) = last {
+ outline.set("Last", n);
+ }
+
+ outline.set("Count", Object::Integer(count));
+
+ for (obj_id, obj) in processed.drain() {
+ self.objects.insert(obj_id, obj.into());
+ }
+
+ self.objects.insert(id, outline.into());
+ self.max_id = maxid;
+ return Some(id);
+ }
+
+ None
+ }
+}
diff --git a/vendor/lopdf/src/cmap_section.rs b/vendor/lopdf/src/cmap_section.rs
new file mode 100644
index 000000000..1bd3cf0d2
--- /dev/null
+++ b/vendor/lopdf/src/cmap_section.rs
@@ -0,0 +1,28 @@
+/*
+ToUnicode CMaps are special CMaps and thus can be parsed simpler. Assumptions:
+- /CMapType is always 2
+- only bfchar and bfrange sections allowed
+- no glyph names as target allowed, only hex strings
+- target encoded in UTF16-BE
+ */
+
+pub(crate) type ArrayOfTargetStrings = Vec<Vec<u16>>;
+
+// According to pdf documentation source codes can be of various byte length but they
+// should be smaller than integer
+pub(crate) type SourceCode = u32;
+pub(crate) type CodeLen = u8;
+pub(crate) type SourceRangeMapping = ((SourceCode, SourceCode, CodeLen), ArrayOfTargetStrings);
+pub(crate) type SourceCharMapping = ((SourceCode, CodeLen), Vec<u16>);
+#[derive(Debug, PartialEq)]
+pub enum CMapSection {
+ CsRange(Vec<(SourceCode, SourceCode, CodeLen)>),
+ BfChar(Vec<SourceCharMapping>),
+ BfRange(Vec<SourceRangeMapping>),
+}
+
+#[derive(Debug)]
+pub enum CMapParseError {
+ Incomplete,
+ Error,
+}
diff --git a/vendor/lopdf/src/common_data_structures/mod.rs b/vendor/lopdf/src/common_data_structures/mod.rs
new file mode 100644
index 000000000..c48d83e2e
--- /dev/null
+++ b/vendor/lopdf/src/common_data_structures/mod.rs
@@ -0,0 +1,106 @@
+use crate::{
+ Error, Object, Result, StringFormat,
+ encodings::{self, bytes_to_string},
+};
+
+/// Creates a text string.
+/// If the input only contains ASCII characters, the string is encoded
+/// in PDFDocEncoding, otherwise in UTF-16BE.
+pub fn text_string(text: &str) -> Object {
+ if text.is_ascii() {
+ return Object::String(text.into(), StringFormat::Literal);
+ }
+ let mut string = Vec::new();
+ encodings::encode_utf16_be(text, &mut string);
+ Object::String(string, StringFormat::Hexadecimal)
+}
+
+/// Decodes a text string.
+/// Depending on the BOM at the start of the string, a different encoding is chosen.
+/// All encodings specified in PDF2.0 are supported (PDFDocEncoding, UTF-16BE,
+/// and UTF-8).
+pub fn decode_text_string(obj: &Object) -> Result<String> {
+ let s = obj.as_str()?;
+ if s.starts_with(b"\xFE\xFF") {
+ // Detected UTF-16BE BOM
+ String::from_utf16(
+ &s[2..]
+ .chunks(2)
+ .map(|c| {
+ if c.len() == 1 {
+ u16::from_be_bytes([c[0], 0])
+ } else {
+ u16::from_be_bytes(c.try_into().unwrap())
+ }
+ })
+ .collect::<Vec<u16>>(),
+ )
+ .map_err(|_| Error::TextStringDecode)
+ } else if s.starts_with(b"\xEF\xBB\xBF") {
+ // Detected UTF-8 BOM
+ String::from_utf8(s.to_vec()).map_err(|_| Error::TextStringDecode)
+ } else {
+ // If neither BOM is detected, PDFDocEncoding is used
+ let mut out = String::new();
+ bytes_to_string(&encodings::PDF_DOC_ENCODING, s, &mut out)?;
+ Ok(out)
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use crate::{
+ Object, StringFormat, common_data_structures::decode_text_string, encodings, text_string, writer::Writer,
+ };
+
+ #[test]
+ fn spec_example1_encode() {
+ let input = "text‰";
+ let text_string = encodings::string_to_bytes(&encodings::PDF_DOC_ENCODING, input);
+ // let text_string = input.bytes().collect::<Vec<_>>();
+ let dict = Object::Dictionary(dictionary!(
+ "Key" => Object::String(text_string, StringFormat::Literal),
+ ));
+ let mut actual = vec![];
+ Writer::write_object(&mut actual, &dict).unwrap();
+ // "\x8B" is equivalent to the escaped version "\\213" which is used
+ // in the original example.
+ let expected = b"<</Key(text\x8B)>>";
+ assert_eq!(actual.as_slice(), expected);
+ }
+
+ #[test]
+ fn spec_example1_decode() {
+ let input = b"<</Key(text\\213)>>";
+ let dict = crate::parser::direct_object(input).unwrap();
+ let dict = dict.as_dict().unwrap();
+ let actual = decode_text_string(dict.get(b"Key").unwrap()).unwrap();
+ let expected = "text‰";
+ assert_eq!(&actual, expected);
+ }
+
+ #[test]
+ fn spec_example2_encode() {
+ // Russian for "test"
+ let input = "тест";
+ // let text_string = encodings::string_to_bytes(encodings::PDF_DOC_ENCODING, input);
+ let dict = Object::Dictionary(dictionary!(
+ "Key" => text_string(input),
+ ));
+ let mut actual = vec![];
+ Writer::write_object(&mut actual, &dict).unwrap();
+ let expected = b"<</Key<FEFF0442043504410442>>>";
+ assert_eq!(actual.as_slice(), expected);
+ }
+
+ #[test]
+ fn spec_example2_decode() {
+ let input = b"<</Key<FEFF0442043504410442>>>";
+ let dict = crate::parser::direct_object(input).unwrap();
+ let dict = dict.as_dict().unwrap();
+ let actual = decode_text_string(dict.get(b"Key").unwrap()).unwrap();
+ // Russian for "test"
+ let expected = "тест";
+ assert_eq!(&actual, expected);
+ }
+}
diff --git a/vendor/lopdf/src/content.rs b/vendor/lopdf/src/content.rs
new file mode 100644
index 000000000..9ff45c983
--- /dev/null
+++ b/vendor/lopdf/src/content.rs
@@ -0,0 +1,46 @@
+use super::Object;
+use crate::Result;
+use crate::writer::Writer;
+use std::io::Write;
+
+#[derive(Debug, Clone)]
+pub struct Operation {
+ pub operator: String,
+ pub operands: Vec<Object>,
+}
+
+impl Operation {
+ pub fn new(operator: &str, operands: Vec<Object>) -> Operation {
+ Operation {
+ operator: operator.to_string(),
+ operands,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Content<Operations: AsRef<[Operation]> = Vec<Operation>> {
+ pub operations: Operations,
+}
+
+impl<Operations: AsRef<[Operation]>> Content<Operations> {
+ /// Encode content operations.
+ pub fn encode(&self) -> Result<Vec<u8>> {
+ let mut buffer = Vec::new();
+ let mut first_operation = true;
+ for operation in self.operations.as_ref() {
+ // Add new line after each operation except the last one.
+ if first_operation {
+ first_operation = false;
+ } else {
+ buffer.write_all(b"\n")?;
+ }
+ for operand in &operation.operands {
+ Writer::write_object(&mut buffer, operand)?;
+ buffer.write_all(b" ")?;
+ }
+ buffer.write_all(operation.operator.as_bytes())?;
+ }
+ Ok(buffer)
+ }
+}
diff --git a/vendor/lopdf/src/creator.rs b/vendor/lopdf/src/creator.rs
new file mode 100644
index 000000000..ecdaa4164
--- /dev/null
+++ b/vendor/lopdf/src/creator.rs
@@ -0,0 +1,431 @@
+use crate::Result;
+use crate::{Dictionary, Document, Object, ObjectId};
+#[cfg(feature = "font_embedding")]
+use crate::{FontData, Stream};
+
+impl Document {
+ /// Create new PDF document with version.
+ pub fn with_version<S: Into<String>>(version: S) -> Document {
+ let mut document = Self::new();
+ document.version = version.into();
+ document
+ }
+
+ /// Create an object ID.
+ pub fn new_object_id(&mut self) -> ObjectId {
+ self.max_id += 1;
+ (self.max_id, 0)
+ }
+
+ /// Add PDF object into document's object list.
+ pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
+ self.max_id += 1;
+ let id = (self.max_id, 0);
+ self.objects.insert(id, object.into());
+ id
+ }
+
+ pub fn set_object<T: Into<Object>>(&mut self, id: ObjectId, object: T) {
+ self.objects.insert(id, object.into());
+ }
+
+ /// Remove PDF object from document's object list.
+ ///
+ /// Other objects may still hold references to this object! Therefore, removing the object might
+ /// lead to dangling references.
+ pub fn remove_object(&mut self, object_id: &ObjectId) -> Result<()> {
+ self.objects.remove(object_id);
+ Ok(())
+ }
+
+ /// Remove annotation from the document.
+ ///
+ /// References to this annotation are removed from the pages' lists of annotations. Finally, the
+ /// annotation object itself is removed.
+ pub fn remove_annot(&mut self, object_id: &ObjectId) -> Result<()> {
+ for (_, page_id) in self.get_pages() {
+ let page = self.get_object_mut(page_id)?.as_dict_mut()?;
+ let annots = page.get_mut(b"Annots")?.as_array_mut()?;
+
+ annots.retain(|object| {
+ if let Ok(id) = object.as_reference() {
+ return id != *object_id;
+ }
+
+ true
+ });
+ }
+
+ self.remove_object(object_id)?;
+
+ Ok(())
+ }
+
+ /// Get the page's resource dictionary.
+ ///
+ /// Get Object that has the key "Resources".
+ pub fn get_or_create_resources(&mut self, page_id: ObjectId) -> Result<&mut Object> {
+ let resources_id = {
+ let page = self.get_object(page_id).and_then(Object::as_dict)?;
+ if page.has(b"Resources") {
+ page.get(b"Resources").and_then(Object::as_reference).ok()
+ } else {
+ None
+ }
+ };
+ if let Some(res_id) = resources_id {
+ return self.get_object_mut(res_id);
+ }
+ let page = self.get_object_mut(page_id).and_then(Object::as_dict_mut)?;
+ if !page.has(b"Resources") {
+ page.set(b"Resources", Dictionary::new());
+ }
+ page.get_mut(b"Resources")
+ }
+
+ /// Add XObject to a page.
+ ///
+ /// Get Object that has the key `Resources -> XObject`.
+ pub fn add_xobject<N: Into<Vec<u8>>>(
+ &mut self, page_id: ObjectId, xobject_name: N, xobject_id: ObjectId,
+ ) -> Result<()> {
+ if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
+ if !resources.has(b"XObject") {
+ resources.set("XObject", Dictionary::new());
+ }
+ let mut xobjects = resources.get_mut(b"XObject")?;
+ if let Object::Reference(xobjects_ref_id) = xobjects {
+ let mut xobjects_id = *xobjects_ref_id;
+ while let Object::Reference(id) = self.get_object(xobjects_id)? {
+ xobjects_id = *id;
+ }
+ xobjects = self.get_object_mut(xobjects_id)?;
+ }
+ let xobjects = Object::as_dict_mut(xobjects)?;
+ xobjects.set(xobject_name, Object::Reference(xobject_id));
+ }
+ Ok(())
+ }
+
+ /// Add Graphics State to a page.
+ ///
+ /// Get Object that has the key `Resources -> ExtGState`.
+ pub fn add_graphics_state<N: Into<Vec<u8>>>(
+ &mut self, page_id: ObjectId, gs_name: N, gs_id: ObjectId,
+ ) -> Result<()> {
+ if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
+ if !resources.has(b"ExtGState") {
+ resources.set("ExtGState", Dictionary::new());
+ }
+ let states = resources.get_mut(b"ExtGState").and_then(Object::as_dict_mut)?;
+ states.set(gs_name, Object::Reference(gs_id));
+ }
+ Ok(())
+ }
+
+ /// Add font to a page.
+ /// # Examples
+ ///
+ /// ```no_run
+ /// // Assuming you have a font file at "./SomeFont.ttf"
+ /// use lopdf::dictionary;
+ ///
+ /// let font_file = std::fs::read("./SomeFont.ttf").unwrap();
+ ///
+ /// // Create a new FontData instance with the font file.
+ /// let font_name = "SomeFont".to_string();
+ /// let mut font_data = lopdf::FontData::new(&font_file, font_name.clone());
+ ///
+ /// // Customize the font data if needed.
+ /// font_data
+ /// .set_italic_angle(10)
+ /// .set_encoding("WinAnsiEncoding".to_string());
+ ///
+ ///
+ /// // Create a new PDF document.
+ /// let mut doc = lopdf::Document::with_version("1.5");
+ ///
+ /// // Add the font to the document.
+ /// let font_id = doc.add_font(font_data).unwrap();
+ ///
+ /// // Now you can use `font_id` to reference the font in your PDF content.
+ /// // For example:
+ /// let resources_id = doc.add_object(dictionary! {
+ /// "Font" => dictionary! {
+ /// font_name => font_id,
+ /// },
+ /// });
+ /// ```
+ #[cfg(feature = "font_embedding")]
+ pub fn add_font(&mut self, font_data: FontData) -> Result<ObjectId> {
+ // Create embedded font stream
+ let font_stream = Stream::new(
+ dictionary! {
+ "Length1" => Object::Integer(font_data.bytes().len() as i64),
+ },
+ font_data.bytes(),
+ );
+ let font_file_id = self.add_object(font_stream);
+ let font_name = font_data.font_name.clone();
+
+ // Create font descriptor dictionary
+ let font_descriptor_id = self.add_object(dictionary! {
+ "Type" => "FontDescriptor",
+ "FontName" => Object::Name(font_name.clone().into_bytes()),
+ "Flags" => Object::Integer(font_data.flags),
+ "FontBBox" => Object::Array(vec![
+ Object::Integer(font_data.font_bbox.0),
+ Object::Integer(font_data.font_bbox.1),
+ Object::Integer(font_data.font_bbox.2),
+ Object::Integer(font_data.font_bbox.3),
+ ]),
+ "ItalicAngle" => Object::Integer(font_data.italic_angle),
+ "Ascent" => Object::Integer(font_data.ascent),
+ "Descent" => Object::Integer(font_data.descent),
+ "CapHeight" => Object::Integer(font_data.cap_height),
+ "StemV" => Object::Integer(font_data.stem_v),
+ "FontFile2" => Object::Reference(font_file_id),
+ });
+
+ // Create font dictionary
+ let font_id = self.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "TrueType",
+ "BaseFont" => Object::Name(font_name.clone().into_bytes()),
+ "FontDescriptor" => Object::Reference(font_descriptor_id),
+ "Encoding" => Object::Name(font_data.encoding.into_bytes()),
+ });
+
+ if let Some(first_char) = font_data.first_char {
+ self.get_dictionary_mut(font_id)
+ .unwrap()
+ .set("FirstChar", Object::Integer(first_char));
+ }
+ if let Some(last_char) = font_data.last_char {
+ self.get_dictionary_mut(font_id)
+ .unwrap()
+ .set("LastChar", Object::Integer(last_char));
+ }
+ if let Some(widths_array) = font_data.widths {
+ let widths = widths_array.into_iter().map(Object::Integer).collect();
+ self.get_dictionary_mut(font_id)
+ .unwrap()
+ .set("Widths", Object::Array(widths));
+ }
+
+ Ok(font_id)
+ }
+}
+
+#[cfg(test)]
+pub mod tests {
+ use std::path::PathBuf;
+
+ #[cfg(feature = "font_embedding")]
+ use crate::FontData;
+ use crate::content::*;
+ use crate::{Document, Object, Stream};
+
+ #[cfg(not(feature = "time"))]
+ pub fn get_timestamp() -> Object {
+ Object::string_literal("D:19700101000000Z")
+ }
+
+ #[cfg(feature = "time")]
+ pub fn get_timestamp() -> Object {
+ time::OffsetDateTime::now_utc().into()
+ }
+
+ /// Create and return a document for testing
+ pub fn create_document() -> Document {
+ create_document_with_texts(&["Hello World!"])
+ }
+
+ pub fn create_document_with_texts(texts_for_pages: &[&str]) -> Document {
+ let mut doc = Document::with_version("1.5");
+ let info_id = doc.add_object(dictionary! {
+ "Title" => Object::string_literal("Create PDF document example"),
+ "Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
+ "CreationDate" => get_timestamp(),
+ });
+ let pages_id = doc.new_object_id();
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Courier",
+ });
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+ let contents = texts_for_pages.iter().map(|text| Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ Operation::new("Tj", vec![Object::string_literal(*text)]),
+ Operation::new("ET", vec![]),
+ ],
+ });
+
+ let pages = contents.map(|content| {
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+ let page = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ });
+ page.into()
+ });
+
+ let pages = dictionary! {
+ "Type" => "Pages",
+ "Kids" => pages.collect::<Vec<Object>>(),
+ "Count" => 1,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![Object::string_literal(b"ABC"), Object::string_literal(b"DEF")]),
+ );
+ doc.compress();
+ doc
+ }
+
+ /// Create a single-page document whose content stream is the
+ /// caller-supplied list of operations (wrapped in `BT`/`ET` if not
+ /// already). Used by tests that need to exercise specific
+ /// content-stream operators not produced by `create_document_with_texts`.
+ pub fn create_document_with_operations(operations: Vec<Operation>) -> Document {
+ let mut doc = Document::with_version("1.5");
+ let info_id = doc.add_object(dictionary! {
+ "Title" => Object::string_literal("Create PDF document example"),
+ "Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
+ "CreationDate" => get_timestamp(),
+ });
+ let pages_id = doc.new_object_id();
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Courier",
+ });
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+ let content = Content { operations };
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+ let page = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ });
+ let pages = dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page.into()],
+ "Count" => 1,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![Object::string_literal(b"ABC"), Object::string_literal(b"DEF")]),
+ );
+ doc.compress();
+ doc
+ }
+
+ /// Save a document
+ pub fn save_document(file_path: &PathBuf, doc: &mut Document) {
+ let res = doc.save(file_path);
+
+ assert!(match res {
+ Ok(_file) => true,
+ Err(_e) => false,
+ });
+ }
+
+ #[test]
+ fn save_created_document() {
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir().unwrap();
+ let file_path = temp_dir.path().join("test_1_create.pdf");
+
+ let mut doc = create_document();
+ // Save to file
+ save_document(&file_path, &mut doc);
+ assert!(file_path.exists());
+ }
+
+ #[cfg(feature = "font_embedding")]
+ #[test]
+ fn test_add_font_embeds_font_correctly() {
+ // Create a dummy TTF font in memory (fake content, just to test structure)
+ let font_file = std::fs::read("./assets/fonts/Montserrat-Regular.ttf").unwrap();
+
+ // Construct FontData manually
+ let mut font_data = FontData::new(&font_file, "MyFont".to_string());
+ font_data
+ .set_flags(32)
+ .set_font_bbox((0, -200, 1000, 800))
+ .set_italic_angle(0)
+ .set_ascent(750)
+ .set_descent(-250)
+ .set_cap_height(700)
+ .set_stem_v(80)
+ .set_encoding("WinAnsiEncoding".to_string());
+
+ // Create PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Create dummy page
+ let page_id = doc.new_object_id();
+ doc.set_object(page_id, dictionary! {});
+
+ // Add font
+ let font_id = doc.add_font(font_data.clone()).unwrap();
+
+ // Font dictionary must exist
+ let font_obj = doc.get_object(font_id).unwrap();
+ let font_dict = font_obj.as_dict().unwrap();
+
+ // Check base font name
+ assert_eq!(font_dict.get(b"BaseFont").unwrap(), &Object::Name(b"MyFont".to_vec()));
+
+ // Check encoding
+ assert_eq!(
+ font_dict.get(b"Encoding").unwrap(),
+ &Object::Name(b"WinAnsiEncoding".to_vec())
+ );
+
+ // Check font descriptor exists and is referenced
+ let descriptor_ref = font_dict.get(b"FontDescriptor").unwrap().as_reference().unwrap();
+ let descriptor_obj = doc.get_object(descriptor_ref).unwrap().as_dict().unwrap();
+ assert_eq!(
+ descriptor_obj.get(b"FontName").unwrap(),
+ &Object::Name(b"MyFont".to_vec())
+ );
+
+ // Check font file is embedded
+ let font_file_ref = descriptor_obj.get(b"FontFile2").unwrap().as_reference().unwrap();
+ let font_stream = doc.get_object(font_file_ref).unwrap().as_stream().unwrap();
+ assert_eq!(font_stream.content, font_file);
+ }
+}
diff --git a/vendor/lopdf/src/datetime.rs b/vendor/lopdf/src/datetime.rs
new file mode 100644
index 000000000..7a7c1733f
--- /dev/null
+++ b/vendor/lopdf/src/datetime.rs
@@ -0,0 +1,381 @@
+use super::Object;
+
+#[cfg(feature = "chrono")]
+mod chrono_impl {
+ use crate::{Object, datetime::convert_utc_offset};
+ use chrono::prelude::*;
+
+ impl From<DateTime<FixedOffset>> for Object {
+ fn from(date: DateTime<FixedOffset>) -> Self {
+ let mut timezone_str = date.format("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
+ convert_utc_offset(&mut timezone_str);
+ Object::string_literal(timezone_str)
+ }
+ }
+
+ impl From<DateTime<Utc>> for Object {
+ fn from(date: DateTime<Utc>) -> Self {
+ Object::string_literal(date.format("D:%Y%m%d%H%M%SZ").to_string())
+ }
+ }
+
+ /// A PDF date states a fixed offset from UT and never a named zone
+ /// (ISO 32000-1, 7.9.4), so this is the conversion that keeps what the
+ /// file said. Re-expressing it in the machine's own zone is what the
+ /// `chrono-clock` feature adds.
+ impl TryFrom<super::DateTime> for DateTime<FixedOffset> {
+ type Error = chrono::format::ParseError;
+
+ fn try_from(value: super::DateTime) -> Result<DateTime<FixedOffset>, Self::Error> {
+ let from_date = |date: NaiveDate| {
+ FixedOffset::east_opt(0)
+ .unwrap()
+ .from_utc_datetime(&date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap()))
+ };
+
+ DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S%#z")
+ .or_else(|_| DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%#z"))
+ .or_else(|_| NaiveDate::parse_from_str(&value.0, "%Y%m%d").map(from_date))
+ }
+ }
+}
+
+/// The system-local conversions, kept apart from `chrono` because `Local`
+/// exists only with chrono's `clock` feature — which brings `iana-time-zone`
+/// and its per-platform chain. A PDF date never names a zone, so a consumer
+/// that does not want the reading machine's offset applied to someone else's
+/// document can have dates for `chrono` and `num-traits` alone.
+#[cfg(feature = "chrono-clock")]
+mod chrono_clock_impl {
+ use crate::{Object, datetime::convert_utc_offset};
+ use chrono::prelude::*;
+
+ impl From<DateTime<Local>> for Object {
+ fn from(date: DateTime<Local>) -> Self {
+ let mut timezone_str = date.format("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
+ convert_utc_offset(&mut timezone_str);
+ Object::string_literal(timezone_str)
+ }
+ }
+
+ impl TryFrom<super::DateTime> for DateTime<Local> {
+ type Error = chrono::format::ParseError;
+
+ fn try_from(value: super::DateTime) -> Result<DateTime<Local>, Self::Error> {
+ DateTime::<FixedOffset>::try_from(value).map(|date| date.with_timezone(&Local))
+ }
+ }
+}
+
+#[cfg(feature = "jiff")]
+mod jiff_impl {
+ use crate::{Object, datetime::convert_utc_offset};
+ use jiff::{Timestamp, Zoned};
+
+ impl From<Zoned> for Object {
+ fn from(date: Zoned) -> Self {
+ let mut timezone_str = date.strftime("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
+ convert_utc_offset(&mut timezone_str);
+ Object::string_literal(timezone_str)
+ }
+ }
+
+ impl From<Timestamp> for Object {
+ fn from(date: Timestamp) -> Self {
+ Object::string_literal(date.strftime("D:%Y%m%d%H%M%SZ").to_string())
+ }
+ }
+
+ impl TryFrom<super::DateTime> for Zoned {
+ type Error = jiff::Error;
+
+ fn try_from(value: super::DateTime) -> Result<Self, Self::Error> {
+ use jiff::civil::{Date, DateTime};
+
+ // We attempt to parse different date time formats based on Section 7.9.4 "Dates" in
+ // PDF 32000-1:2008 here.
+ //
+ // "A PLUS SIGN as the value of the O field signifies that the local time is later than
+ // UT, a HYPHEN-MINUS signifies that local time is earlier than UT, and the LATIN
+ // CAPITAL Z signifies that local time is equal to UT. If no UT information is
+ // specified, the relationship of the specified time to UT shall be considered GMT."
+ //
+ // 1. Try parsing the full date and time with the `%#z` specifier to parse the timezone as a `Zoned` object.
+ // 2. Try parsing the full date and time with the 'Z' suffix as a `DateTime` interpreted to be in the UTC
+ // timezone.
+ // 3. Try parsing the date and time without the seconds specified with the `%#z` specifier to parse the
+ // timezone as a `Zoned` object.
+ // 4. Try parsing the date and time without the seconds specified with the 'Z' as a `DateTime` interpreted
+ // to be in the UTC timezone.
+ // 5. Try parsing the date with no time as a `Date` interpreted to be in the GMT timezone.
+ //
+ // In all cases we return a `Zoned` object here to preserve the timezone.
+ Zoned::strptime("%Y%m%d%H%M%S%#z", &value.0)
+ .or_else(|_| DateTime::strptime("%Y%m%d%H%M%SZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
+ .or_else(|_| Zoned::strptime("%Y%m%d%H%M%#z", &value.0))
+ .or_else(|_| DateTime::strptime("%Y%m%d%H%MZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
+ .or_else(|_| Date::strptime("%Y%m%d", &value.0).and_then(|dt| dt.at(0, 0, 0, 0).in_tz("GMT")))
+ }
+ }
+}
+
+#[cfg(feature = "time")]
+mod time_impl {
+ use crate::Object;
+ use time::{OffsetDateTime, PrimitiveDateTime};
+
+ /// The naive datetime is taken to be UTC and rendered with the `Z` suffix
+ /// (PDF 32000-1 §7.9.4) — the `time`-crate counterpart of the
+ /// `chrono::DateTime<Utc>` and `jiff::Timestamp` impls above.
+ ///
+ /// (This replaces a `From<time::Time>` impl that never compiled — see
+ /// issue #518: it referenced a nonexistent `FormatItem::StringLiteral`
+ /// with a strftime pattern, and a bare time-of-day cannot form a valid
+ /// PDF date anyway, which must start at the year.)
+ impl From<PrimitiveDateTime> for Object {
+ fn from(date: PrimitiveDateTime) -> Self {
+ Object::string_literal({
+ // D:%Y%m%d%H%M%SZ
+ let format =
+ time::format_description::parse_borrowed::<3>("D:[year][month][day][hour][minute][second]Z")
+ .unwrap();
+ date.format(&format).unwrap()
+ })
+ }
+ }
+
+ impl From<OffsetDateTime> for Object {
+ fn from(date: OffsetDateTime) -> Self {
+ Object::string_literal({
+ // D:%Y%m%d%H%M%S:%z'
+ let format = time::format_description::parse_borrowed::<3>(
+ "D:[year][month][day][hour][minute][second][offset_hour sign:mandatory]'[offset_minute]'",
+ )
+ .unwrap();
+ date.format(&format).unwrap()
+ })
+ }
+ }
+
+ /// WARNING: `tm_wday` (weekday), `tm_yday` (day index in year), `tm_isdst`
+ /// (daylight saving time) and `tm_nsec` (nanoseconds of the date from 1970)
+ /// are set to 0 since they aren't available in the PDF time format. They could,
+ /// however, be calculated manually
+ impl TryFrom<super::DateTime> for OffsetDateTime {
+ type Error = time::Error;
+
+ fn try_from(value: super::DateTime) -> Result<OffsetDateTime, Self::Error> {
+ let format = time::format_description::parse_borrowed::<3>(
+ "[year][month][day][hour][minute][second][offset_hour sign:mandatory][offset_minute]",
+ )
+ .unwrap();
+
+ Ok(OffsetDateTime::parse(&value.0, &format)?)
+ }
+ }
+}
+
+// Find the last `:` and turn it into an `'` to account for PDF weirdness
+#[allow(dead_code)]
+fn convert_utc_offset(bytes: &mut [u8]) {
+ let mut index = bytes.len();
+ while let Some(last) = bytes[..index].last_mut() {
+ if *last == b':' {
+ *last = b'\'';
+ break;
+ }
+ index -= 1;
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct DateTime(String);
+
+impl Object {
+ // Parses the `D`, `:` and `\` out of a `Object::String` to parse the date time
+ fn datetime_string(&self) -> Option<String> {
+ if let Object::String(bytes, _) = self {
+ String::from_utf8(bytes.iter().filter(|b| !b"D:'".contains(b)).cloned().collect()).ok()
+ } else {
+ None
+ }
+ }
+
+ pub fn as_datetime(&self) -> Option<DateTime> {
+ self.datetime_string().map(DateTime)
+ }
+}
+
+impl DateTime {
+ /// The date's characters with `D`, `:` and `'` removed.
+ ///
+ /// Every typed conversion of this value needs a date backend — `chrono`,
+ /// `jiff` or `time` — but [`Object::as_datetime`] itself needs none. A
+ /// build that enables no backend could therefore obtain a `DateTime` and
+ /// have no way to read it. This is that way.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+#[test]
+fn a_datetime_is_readable_without_a_backend() {
+ let text = Object::string_literal("D:20260710143000+02'00'");
+ // The `D`, `:` and apostrophes are filtered out on the way in; the
+ // relation sign survives, because it is what the offset means.
+ assert_eq!(text.as_datetime().unwrap().as_str(), "20260710143000+0200");
+ assert!(Object::Integer(20260710).as_datetime().is_none());
+}
+
+#[cfg(feature = "chrono")]
+#[test]
+fn parse_datetime_fixed_offset_keeps_the_offset_the_file_stated() {
+ use chrono::prelude::*;
+
+ let text = Object::string_literal("D:20260710143000+02'00'");
+ let date: DateTime<FixedOffset> = text.as_datetime().unwrap().try_into().unwrap();
+ // Not shifted into UTC, and not into the reading machine's zone either.
+ assert_eq!(date.offset().local_minus_utc(), 2 * 3600);
+ assert_eq!(date.hour(), 14);
+ // And it round-trips back to the same text.
+ let back: Object = date.into();
+ assert_eq!(back, Object::string_literal("D:20260710143000+02'00'"));
+}
+
+#[cfg(feature = "chrono")]
+#[test]
+fn parse_datetime_fixed_offset_round_trip() {
+ use chrono::prelude::*;
+
+ // A fixed instant rather than `now()`: `Utc::now` needs chrono's `clock`
+ // feature, which this row deliberately does without, and a deterministic
+ // test is the better one regardless.
+ let time = FixedOffset::east_opt(-5 * 3600 - 30 * 60)
+ .unwrap()
+ .with_ymd_and_hms(2026, 7, 10, 14, 30, 0)
+ .unwrap();
+ let text: Object = time.into();
+ let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert_eq!(time2, Some(time));
+}
+
+#[cfg(feature = "chrono-clock")]
+#[test]
+fn parse_datetime_local() {
+ use chrono::prelude::*;
+
+ let time = Local::now().with_nanosecond(0).unwrap();
+ let text: Object = time.into();
+ let time2: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert_eq!(time2, Some(time));
+}
+
+#[cfg(feature = "chrono")]
+#[test]
+fn parse_datetime_utc() {
+ use chrono::prelude::*;
+
+ let time = Utc.with_ymd_and_hms(2026, 7, 10, 14, 30, 0).unwrap();
+ let text: Object = time.into();
+ let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert_eq!(time2, Some(time.fixed_offset()));
+}
+
+#[cfg(feature = "jiff")]
+#[test]
+fn parse_zoned() {
+ use jiff::Zoned;
+
+ let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
+ let text: Object = time.clone().into();
+ let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert_eq!(time2, Some(time));
+}
+
+#[cfg(feature = "jiff")]
+#[test]
+fn parse_timestamp() {
+ use jiff::Zoned;
+
+ let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
+ let text: Object = time.timestamp().into();
+ let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert_eq!(time2, Some(time));
+}
+
+#[cfg(feature = "chrono")]
+#[test]
+fn parse_datetime_seconds_missing_chrono() {
+ use chrono::prelude::*;
+
+ // this is the example from the PDF reference, version 1.7, chapter 3.8.3
+ let text = Object::string_literal("D:199812231952-08'00'");
+ let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert!(dt.is_some());
+}
+
+#[cfg(feature = "chrono")]
+#[test]
+fn parse_datetime_time_missing_chrono() {
+ use chrono::prelude::*;
+
+ let text = Object::string_literal("D:20040229");
+ let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert!(dt.is_some());
+}
+
+#[cfg(feature = "jiff")]
+#[test]
+fn parse_datetime_seconds_missing_jiff() {
+ use jiff::Zoned;
+
+ // this is the example from the PDF reference, version 1.7, chapter 3.8.3
+ let text = Object::string_literal("D:199812231952-08'00'");
+ let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert!(dt.is_some());
+}
+
+#[cfg(feature = "jiff")]
+#[test]
+fn parse_datetime_time_missing_jiff() {
+ use jiff::Zoned;
+
+ let text = Object::string_literal("D:20040229");
+ let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
+ assert!(dt.is_some());
+}
+
+#[cfg(feature = "time")]
+#[test]
+fn format_primitive_datetime_as_utc() {
+ use time::{Date, Month, PrimitiveDateTime, Time};
+
+ // The example date from the PDF reference (1.7, §3.8.3), as a naive
+ // datetime: it must serialize with the year first and the `Z` suffix.
+ let date = Date::from_calendar_date(1998, Month::December, 23).unwrap();
+ let time = Time::from_hms(19, 52, 0).unwrap();
+ let text: Object = PrimitiveDateTime::new(date, time).into();
+ match &text {
+ Object::String(bytes, _) => assert_eq!(bytes.as_slice(), b"D:19981223195200Z"),
+ other => panic!("expected a string literal, got {other:?}"),
+ }
+}
+
+#[cfg(feature = "time")]
+#[test]
+fn parse_datetime() {
+ use time::OffsetDateTime;
+
+ let time = OffsetDateTime::now_utc();
+
+ let text: Object = time.into();
+ let time2: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
+
+ assert_eq!(time2.date(), time.date());
+
+ // Ignore nanoseconds
+ // - not important in the date parsing
+ assert_eq!(time2.time().hour(), time.time().hour());
+ assert_eq!(time2.time().minute(), time.time().minute());
+ assert_eq!(time2.time().second(), time.time().second());
+}
diff --git a/vendor/lopdf/src/destinations.rs b/vendor/lopdf/src/destinations.rs
new file mode 100644
index 000000000..27d1325df
--- /dev/null
+++ b/vendor/lopdf/src/destinations.rs
@@ -0,0 +1,83 @@
+use super::{Dictionary, Document, Object, Result};
+use indexmap::IndexMap;
+#[derive(Debug, Clone)]
+pub struct Destination(Dictionary);
+
+impl Destination {
+ pub fn new(title: Object, page: Object, typ: Object) -> Self {
+ let mut dict = Dictionary::new();
+ dict.set(b"Title", title);
+ dict.set(b"Page", page);
+ dict.set(b"Type", typ);
+ Destination(dict)
+ }
+
+ pub fn set<K, V>(&mut self, key: K, value: V)
+ where
+ K: Into<Vec<u8>>,
+ V: Into<Object>,
+ {
+ self.0.set(key, value);
+ }
+
+ pub fn title(&self) -> Result<&Object> {
+ self.0.get(b"Title")
+ }
+
+ pub fn page(&self) -> Result<&Object> {
+ self.0.get(b"Page")
+ }
+}
+
+impl Document {
+ pub fn get_named_destinations(
+ &self, tree: &Dictionary, named_destinations: &mut IndexMap<Vec<u8>, Destination>,
+ ) -> Result<()> {
+ self.get_named_destinations_impl(tree, named_destinations, 0)
+ }
+
+ fn get_named_destinations_impl(
+ &self, tree: &Dictionary, named_destinations: &mut IndexMap<Vec<u8>, Destination>, depth: usize,
+ ) -> Result<()> {
+ if depth >= crate::reader::MAX_NESTING_DEPTH {
+ return Err(crate::Error::RecursionLimit);
+ }
+ if let Ok(kids) = tree.get(b"Kids") {
+ for kid in kids.as_array()? {
+ if let Ok(kid) = kid.as_reference().and_then(move |id| self.get_dictionary(id)) {
+ self.get_named_destinations_impl(kid, named_destinations, depth + 1)?;
+ }
+ }
+ }
+ if let Ok(names) = tree.get(b"Names") {
+ let mut names = names.as_array()?.iter();
+ loop {
+ let key = names.next();
+ if key.is_none() {
+ break;
+ }
+ let val = names.next();
+ if val.is_none() {
+ break;
+ }
+ if let Ok(obj_ref) = val.unwrap().as_reference() {
+ if let Ok(dict) = self.get_dictionary(obj_ref) {
+ let val = dict.get(b"D").as_ref().unwrap().as_array()?;
+ let dest = Destination::new(key.unwrap().clone(), val[0].clone(), val[1].clone());
+ named_destinations.insert(key.unwrap().as_str().unwrap().to_vec(), dest);
+ } else if let Ok(Object::Array(val)) = self.get_object(obj_ref) {
+ let dest = Destination::new(key.unwrap().clone(), val[0].clone(), val[1].clone());
+ named_destinations.insert(key.unwrap().as_str().unwrap().to_vec(), dest);
+ }
+ } else if let Ok(dict) = val.unwrap().as_dict() {
+ let val = dict.get(b"D").as_ref().unwrap().as_array()?;
+ let dest = Destination::new(key.unwrap().clone(), val[0].clone(), val[1].clone());
+ named_destinations.insert(key.unwrap().as_str().unwrap().to_vec(), dest);
+ } else {
+ // TODO: Log error: Unpexpected node type
+ }
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/vendor/lopdf/src/document.rs b/vendor/lopdf/src/document.rs
new file mode 100644
index 000000000..820fd2f6b
--- /dev/null
+++ b/vendor/lopdf/src/document.rs
@@ -0,0 +1,964 @@
+use super::encodings::Encoding;
+use super::{Bookmark, Dictionary, Object, ObjectId};
+use crate::encryption::crypt_filters::*;
+use crate::encryption::{self, EncryptionState, PasswordAlgorithm};
+use crate::xobject::PdfImage;
+use crate::xref::{Xref, XrefType};
+use crate::{DecompressError, Error, ObjectStream, Result, Stream};
+use log::debug;
+use std::cmp::max;
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::str;
+use std::sync::Arc;
+
+/// A PDF document.
+///
+/// This can both be a combination of multiple incremental updates
+/// or just one (the last) incremental update in a PDF file.
+#[derive(Debug, Clone)]
+pub struct Document {
+ /// The version of the PDF specification to which the file conforms.
+ pub version: String,
+
+ /// The binary mark important for PDF A/2,3 tells various software tools to classify
+ /// the file as containing 8-bit binary that should be preserved during processing
+ pub binary_mark: Vec<u8>,
+
+ /// The trailer gives the location of the cross-reference table and of certain special objects.
+ pub trailer: Dictionary,
+
+ /// The cross-reference table contains locations of the indirect objects.
+ pub reference_table: Xref,
+
+ /// The objects that make up the document contained in the file.
+ pub objects: BTreeMap<ObjectId, Object>,
+
+ /// Current maximum object id within the document.
+ pub max_id: u32,
+
+ /// Current maximum object id within Bookmarks.
+ pub max_bookmark_id: u32,
+
+ /// The bookmarks in the document. Render at the very end of document after renumbering objects.
+ pub bookmarks: Vec<u32>,
+
+ /// used to locate a stored Bookmark so children can be appended to it via its id. Otherwise we
+ /// need to do recursive lookups and returns on the bookmarks internal layout Vec
+ pub bookmark_table: HashMap<u32, Bookmark>,
+
+ /// The byte the cross-reference table starts at.
+ /// This value is only set during reading, but not when writing the file.
+ /// It is used to support incremental updates in PDFs.
+ /// Default value is `0`.
+ pub xref_start: usize,
+
+ /// The encryption state stores the parameters that were used to decrypt this document if the
+ /// document has been decrypted.
+ pub encryption_state: Option<EncryptionState>,
+}
+
+impl Document {
+ /// Create new PDF document.
+ pub fn new() -> Self {
+ Self {
+ version: "1.4".to_string(),
+ binary_mark: vec![0xBB, 0xAD, 0xC0, 0xDE],
+ trailer: Dictionary::new(),
+ reference_table: Xref::new(0, XrefType::CrossReferenceStream),
+ objects: BTreeMap::new(),
+ max_id: 0,
+ max_bookmark_id: 0,
+ bookmarks: Vec::new(),
+ bookmark_table: HashMap::new(),
+ xref_start: 0,
+ encryption_state: None,
+ }
+ }
+
+ /// Create a new PDF document that is an incremental update to a previous document.
+ pub fn new_from_prev(prev: &Document) -> Self {
+ let mut new_trailer = prev.trailer.clone();
+ // A zero xref_start marks a document with no known on-disk table
+ // (e.g. recovered by scanning); emitting `/Prev 0` would corrupt the chain.
+ if prev.xref_start != 0 {
+ new_trailer.set("Prev", Object::Integer(prev.xref_start as i64));
+ }
+ Self {
+ version: "1.4".to_string(),
+ binary_mark: vec![0xBB, 0xAD, 0xC0, 0xDE],
+ trailer: new_trailer,
+ reference_table: Xref::new(0, prev.reference_table.cross_reference_type),
+ objects: BTreeMap::new(),
+ max_id: prev.max_id,
+ max_bookmark_id: prev.max_bookmark_id,
+ bookmarks: Vec::new(),
+ bookmark_table: HashMap::new(),
+ xref_start: 0,
+ encryption_state: None,
+ }
+ }
+
+ const DEREF_LIMIT: usize = 128;
+
+ fn recursive_fix_pages(&mut self, bookmarks: &[u32], first: bool) -> ObjectId {
+ if !bookmarks.is_empty() {
+ for id in bookmarks {
+ let (children, mut page) = match self.bookmark_table.get(id) {
+ Some(n) => (n.children.clone(), n.page),
+ None => return (0, 0),
+ };
+
+ if 0 == page.0 && !children.is_empty() {
+ let objectid = self.recursive_fix_pages(&children[..], false);
+
+ let bookmark = self.bookmark_table.get_mut(id).unwrap();
+ bookmark.page = objectid;
+ page = objectid;
+ }
+
+ if !first && 0 != page.0 {
+ return page;
+ }
+
+ if first && !children.is_empty() {
+ self.recursive_fix_pages(&children[..], first);
+ }
+ }
+ }
+
+ (0, 0)
+ }
+
+ /// Adjusts the Parents that have a ObjectId of (0,_) to that
+ /// of their first child. will recurse through all entries
+ /// till all parents of children are set. This should be
+ /// ran before building the final bookmark objects but after
+ /// renumbering of objects.
+ pub fn adjust_zero_pages(&mut self) {
+ self.recursive_fix_pages(&self.bookmarks.clone(), true);
+ }
+
+ /// Follow references if the supplied object is a reference.
+ ///
+ /// Returns a tuple of an optional object id and final object.
+ /// The object id will be None if the object was not a
+ /// reference. Otherwise, it will be the last object id in the
+ /// reference chain.
+ pub fn dereference<'a>(&'a self, mut object: &'a Object) -> Result<(Option<ObjectId>, &'a Object)> {
+ let mut nb_deref = 0;
+ let mut id = None;
+
+ while let Ok(ref_id) = object.as_reference() {
+ id = Some(ref_id);
+ object = self.objects.get(&ref_id).ok_or(Error::ObjectNotFound(ref_id))?;
+
+ nb_deref += 1;
+ if nb_deref > Self::DEREF_LIMIT {
+ return Err(Error::ReferenceLimit);
+ }
+ }
+
+ Ok((id, object))
+ }
+
+ /// Get object by object id, will iteratively dereference a referenced object.
+ pub fn get_object(&self, id: ObjectId) -> Result<&Object> {
+ let object = self.objects.get(&id).ok_or(Error::ObjectNotFound(id))?;
+ self.dereference(object).map(|(_, object)| object)
+ }
+
+ /// Determines if an object exists in the current document (or incremental update.)
+ /// with the given `ObjectId`.
+ /// `true` if the object exists, `false` if it does not exist.
+ pub fn has_object(&self, id: ObjectId) -> bool {
+ self.objects.contains_key(&id)
+ }
+
+ /// Get mutable reference to object by object ID, will iteratively dereference a referenced object.
+ pub fn get_object_mut(&mut self, id: ObjectId) -> Result<&mut Object> {
+ let object = self.objects.get(&id).ok_or(Error::ObjectNotFound(id))?;
+ let (ref_id, _obj) = self.dereference(object)?;
+
+ Ok(self.objects.get_mut(&ref_id.unwrap_or(id)).unwrap())
+ }
+
+ /// Get the object ID of the page that contains `id`.
+ pub fn get_object_page(&self, id: ObjectId) -> Result<ObjectId> {
+ for (_, object_id) in self.get_pages() {
+ let page = self.get_object(object_id)?.as_dict()?;
+ let annots = page.get(b"Annots")?.as_array()?;
+ let mut objects_ids = annots.iter().map(Object::as_reference);
+
+ let contains = objects_ids.any(|object_id| Some(id) == object_id.ok());
+ if contains {
+ return Ok(object_id);
+ }
+ }
+
+ Err(Error::PageNumberNotFound(0))
+ }
+
+ /// Get dictionary object by id.
+ pub fn get_dictionary(&self, id: ObjectId) -> Result<&Dictionary> {
+ self.get_object(id).and_then(Object::as_dict)
+ }
+
+ /// Get a mutable dictionary object by id.
+ pub fn get_dictionary_mut(&mut self, id: ObjectId) -> Result<&mut Dictionary> {
+ self.get_object_mut(id).and_then(Object::as_dict_mut)
+ }
+
+ /// Get dictionary in dictionary by key.
+ pub fn get_dict_in_dict<'a>(&'a self, node: &'a Dictionary, key: &[u8]) -> Result<&'a Dictionary> {
+ match node.get(key)? {
+ Object::Reference(object_id) => self.get_dictionary(*object_id),
+ Object::Dictionary(dic) => Ok(dic),
+ obj => Err(Error::ObjectType {
+ expected: "Dictionary",
+ found: obj.enum_variant(),
+ }),
+ }
+ }
+
+ /// Traverse objects from trailer recursively, return all referenced object IDs.
+ pub fn traverse_objects<A: Fn(&mut Object)>(&mut self, action: A) -> Vec<ObjectId> {
+ fn traverse_array<A: Fn(&mut Object)>(array: &mut [Object], action: &A, refs: &mut Vec<ObjectId>) {
+ for item in array.iter_mut() {
+ traverse_object(item, action, refs);
+ }
+ }
+ fn traverse_dictionary<A: Fn(&mut Object)>(dict: &mut Dictionary, action: &A, refs: &mut Vec<ObjectId>) {
+ for (_, v) in dict.iter_mut() {
+ traverse_object(v, action, refs);
+ }
+ }
+ fn traverse_object<A: Fn(&mut Object)>(object: &mut Object, action: &A, refs: &mut Vec<ObjectId>) {
+ action(object);
+ match object {
+ Object::Array(array) => traverse_array(array, action, refs),
+ Object::Dictionary(dict) => traverse_dictionary(dict, action, refs),
+ Object::Stream(stream) => traverse_dictionary(&mut stream.dict, action, refs),
+ Object::Reference(id) if !refs.contains(id) => {
+ refs.push(*id);
+ }
+ _ => {}
+ }
+ }
+ let mut refs = vec![];
+ traverse_dictionary(&mut self.trailer, &action, &mut refs);
+ let mut index = 0;
+ while index < refs.len() {
+ if let Some(object) = self.objects.get_mut(&refs[index]) {
+ traverse_object(object, &action, &mut refs);
+ }
+ index += 1;
+ }
+ refs
+ }
+
+ /// Return dictionary with encryption information
+ pub fn get_encrypted(&self) -> Result<&Dictionary> {
+ self.trailer
+ .get(b"Encrypt")
+ .and_then(Object::as_reference)
+ .and_then(|id| self.get_dictionary(id))
+ }
+
+ /// Return true if PDF document is currently encrypted
+ pub fn is_encrypted(&self) -> bool {
+ self.get_encrypted().is_ok()
+ }
+
+ /// Return true if the document was originally encrypted when loaded
+ pub fn was_encrypted(&self) -> bool {
+ self.encryption_state.is_some()
+ }
+
+ /// Authenticate the provided owner password directly as bytes without sanitization
+ pub fn authenticate_raw_owner_password<P>(&self, password: P) -> Result<()>
+ where
+ P: AsRef<[u8]>,
+ {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let password = password.as_ref();
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ algorithm.authenticate_owner_password(self, password)?;
+
+ Ok(())
+ }
+
+ /// Authenticate the provided user password directly as bytes without sanitization
+ pub fn authenticate_raw_user_password<P>(&self, password: P) -> Result<()>
+ where
+ P: AsRef<[u8]>,
+ {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let password = password.as_ref();
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ algorithm.authenticate_user_password(self, password)?;
+
+ Ok(())
+ }
+
+ /// Authenticate the provided owner/user password as bytes without sanitization
+ pub fn authenticate_raw_password<P>(&self, password: P) -> Result<()>
+ where
+ P: AsRef<[u8]>,
+ {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let password = password.as_ref();
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ algorithm
+ .authenticate_owner_password(self, password)
+ .or(algorithm.authenticate_user_password(self, password))?;
+
+ Ok(())
+ }
+
+ /// Authenticate the provided owner password
+ pub fn authenticate_owner_password(&self, password: &str) -> Result<()> {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ let password = algorithm.sanitize_password(password)?;
+ algorithm.authenticate_owner_password(self, &password)?;
+
+ Ok(())
+ }
+
+ /// Authenticate the provided user password
+ pub fn authenticate_user_password(&self, password: &str) -> Result<()> {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ let password = algorithm.sanitize_password(password)?;
+ algorithm.authenticate_user_password(self, &password)?;
+
+ Ok(())
+ }
+
+ /// Authenticate the provided owner/user password
+ pub fn authenticate_password(&self, password: &str) -> Result<()> {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let algorithm = PasswordAlgorithm::try_from(self)?;
+ let password = algorithm.sanitize_password(password)?;
+ algorithm
+ .authenticate_owner_password(self, &password)
+ .or(algorithm.authenticate_user_password(self, &password))?;
+
+ Ok(())
+ }
+
+ /// Returns a `BTreeMap` of the crypt filters available in the PDF document if any.
+ pub fn get_crypt_filters(&self) -> BTreeMap<Vec<u8>, Arc<dyn CryptFilter>> {
+ let mut crypt_filters = BTreeMap::new();
+
+ if let Ok(filters) = self
+ .get_encrypted()
+ .and_then(|dict| dict.get(b"CF"))
+ .and_then(|object| object.as_dict())
+ {
+ for (name, filter) in filters {
+ let Ok(filter) = filter.as_dict() else {
+ continue;
+ };
+
+ if filter.get(b"Type").is_ok() && !filter.has_type(b"CryptFilter") {
+ continue;
+ }
+
+ // Get the Crypt Filter Method (CFM) used, if any, by the PDF reader to decrypt data.
+ let cfm = filter.get(b"CFM").and_then(|object| object.as_name()).ok();
+
+ let crypt_filter: Arc<dyn CryptFilter> = match cfm {
+ // The application shall ask the security handler for the file encryption key
+ // and shall implicitly decrypt data using the RC4 algorithm.
+ Some(b"V2") => Arc::new(Rc4CryptFilter),
+ // The application shall ask the security handler for the file encryption key
+ // and shall implicitly decrypt data using the AES-128 algorithm in Cipher
+ // Block Chaining (CBC) mode with a 16-byte block size and an initialization
+ // vector that shall be randomly generated and placed as the first 16 bytes in
+ // the stream or string. The key size (Length) shall be 128 bits.
+ Some(b"AESV2") => Arc::new(Aes128CryptFilter),
+ // The application shall ask the security handler for the file encryption key
+ // and shall implicitly decrypt data using the AES-256 algorithm in Cipher
+ // Block Chaining (CBC) with padding mode with a 16-byte block size and an
+ // initialization vector that is randomly generated and placed as the first 16
+ // bytes in the stream or string. The key size (Length) shall be 256 bits.
+ Some(b"AESV3") => Arc::new(Aes256CryptFilter),
+ // The application shall not decrypt data but shall direct the input stream to
+ // the security handler for decryption.
+ Some(b"Identity") | None => Arc::new(IdentityCryptFilter),
+ // Unknown crypt filter method.
+ _ => continue,
+ };
+
+ crypt_filters.insert(name.to_vec(), crypt_filter);
+ }
+ }
+
+ crypt_filters
+ }
+
+ /// Replaces all encrypted Strings and Streams with their encrypted contents
+ pub fn encrypt(&mut self, state: &EncryptionState) -> Result<()> {
+ if self.is_encrypted() {
+ return Err(Error::AlreadyEncrypted);
+ }
+
+ let encrypted = state.encode()?;
+
+ for (&id, obj) in self.objects.iter_mut() {
+ encryption::encrypt_object(state, id, obj)?;
+ }
+
+ let object_id = self.add_object(encrypted);
+ self.trailer.set(b"Encrypt", Object::Reference(object_id));
+ self.encryption_state = None;
+
+ Ok(())
+ }
+
+ /// Replaces all encrypted Strings and Streams with their decrypted contents
+ pub fn decrypt(&mut self, password: &str) -> Result<()> {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ let algorithm = PasswordAlgorithm::try_from(&*self)?;
+ let password = algorithm.sanitize_password(password)?;
+ self.decrypt_raw(&password)
+ }
+
+ /// Replaces all encrypted Strings and Streams with their decrypted contents with the password
+ /// provided directly as bytes without sanitization
+ pub fn decrypt_raw<P>(&mut self, password: P) -> Result<()>
+ where
+ P: AsRef<[u8]>,
+ {
+ if !self.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ self.authenticate_raw_password(&password)?;
+
+ // Find the ID of the encryption dict; we'll want to skip it when decrypting
+ let encryption_obj_id = self.trailer.get(b"Encrypt").and_then(Object::as_reference)?;
+
+ let mut state = EncryptionState::decode(&*self, password)?;
+
+ for (&id, obj) in self.objects.iter_mut() {
+ // The encryption dictionary is not encrypted, leave it alone
+ if id == encryption_obj_id {
+ continue;
+ }
+
+ encryption::decrypt_object(&state, id, obj)?;
+ }
+
+ // Add the objects from the object streams now that they have been decrypted.
+ let mut object_streams = vec![];
+
+ for object in self.objects.values() {
+ let Ok(stream) = object.as_stream() else {
+ continue;
+ };
+
+ if !stream.dict.has_type(b"ObjStm") {
+ continue;
+ }
+
+ let Some(obj_stream) = ObjectStream::new(stream).ok() else {
+ continue;
+ };
+
+ // TODO: Is insert and replace intended behavior?
+ // See https://github.com/J-F-Liu/lopdf/issues/160 for more info
+ object_streams.extend(obj_stream.objects);
+ }
+
+ // Only add entries, but never replace entries
+ for (id, entry) in object_streams {
+ self.objects.entry(id).or_insert(entry);
+ }
+
+ let object_id = self.trailer.remove(b"Encrypt").unwrap().as_reference()?;
+ self.objects.remove(&object_id);
+
+ // Remember the object id of the original /Encrypt dictionary so that
+ // callers doing an incremental save can point the appended trailer's
+ // /Encrypt back at the (still-intact) dictionary bytes in the previous
+ // revision. See `IncrementalDocument::save_internal`.
+ state.encrypt_object_id = Some(object_id);
+
+ self.encryption_state = Some(state);
+
+ Ok(())
+ }
+
+ /// Return the PDF document catalog, which is the root of the document's object graph.
+ pub fn catalog(&self) -> Result<&Dictionary> {
+ self.trailer
+ .get(b"Root")
+ .and_then(Object::as_reference)
+ .and_then(|id| self.get_dictionary(id))
+ }
+
+ /// Return a mutable reference to the PDF document catalog, which is the root of the document's
+ /// object graph.
+ pub fn catalog_mut(&mut self) -> Result<&mut Dictionary> {
+ self.trailer
+ .get(b"Root")
+ .and_then(Object::as_reference)
+ .and_then(move |id| self.get_dictionary_mut(id))
+ }
+
+ /// Get page numbers and corresponding object ids.
+ pub fn get_pages(&self) -> BTreeMap<u32, ObjectId> {
+ self.page_iter().enumerate().map(|(i, p)| ((i + 1) as u32, p)).collect()
+ }
+
+ pub fn page_iter(&self) -> impl Iterator<Item = ObjectId> + '_ {
+ PageTreeIter::new(self)
+ }
+
+ /// Get content stream object ids of a page.
+ pub fn get_page_contents(&self, page_id: ObjectId) -> Vec<ObjectId> {
+ let mut streams = vec![];
+ if let Ok(page) = self.get_dictionary(page_id) {
+ let mut nb_deref = 0;
+ // Since we're looking for object IDs, we can't use get_deref
+ // so manually walk any references in contents object
+ if let Ok(mut contents) = page.get(b"Contents") {
+ loop {
+ match contents {
+ Object::Reference(id) => match self.objects.get(id) {
+ None | Some(Object::Stream(_)) => {
+ streams.push(*id);
+ }
+ Some(o) => {
+ nb_deref += 1;
+ if nb_deref < Self::DEREF_LIMIT {
+ contents = o;
+ continue;
+ }
+ }
+ },
+ Object::Array(arr) => {
+ for content in arr {
+ if let Ok(id) = content.as_reference() {
+ streams.push(id)
+ }
+ }
+ }
+ _ => {}
+ }
+ break;
+ }
+ }
+ }
+ streams
+ }
+
+ /// Add content to a page. All existing content will be unchanged.
+ pub fn add_page_contents(&mut self, page_id: ObjectId, content: Vec<u8>) -> Result<()> {
+ let page = self.get_dictionary(page_id)?;
+ let mut current_content_list: Vec<Object> = match page.get(b"Contents") {
+ Ok(Object::Reference(id)) => {
+ vec![Object::Reference(*id)]
+ }
+ Ok(Object::Array(arr)) => arr.clone(),
+ _ => vec![],
+ };
+ let content_object_id = self.add_object(Object::Stream(Stream::new(Dictionary::new(), content)));
+ current_content_list.push(Object::Reference(content_object_id));
+
+ let page_mut = self.get_object_mut(page_id).and_then(Object::as_dict_mut)?;
+ page_mut.set("Contents", current_content_list);
+ Ok(())
+ }
+
+ /// Get content of a page.
+ pub fn get_page_content(&self, page_id: ObjectId) -> Vec<u8> {
+ let mut content = Vec::new();
+ let content_streams = self.get_page_contents(page_id);
+ for object_id in content_streams {
+ if let Ok(content_stream) = self.get_object(object_id).and_then(Object::as_stream) {
+ match content_stream.decompressed_content() {
+ Ok(data) => content.extend_from_slice(&data),
+ Err(_) => content.extend_from_slice(&content_stream.content),
+ };
+ content.push(b'\n');
+ }
+ }
+ content
+ }
+
+ /// Get the content of a page, bounding the total decompressed output to
+ /// `max_decompressed_size` bytes.
+ ///
+ /// This is the decompression-bomb-safe counterpart to
+ /// [`Document::get_page_content`]. A page's content can be split across
+ /// several streams; the whole concatenated result is bounded to roughly
+ /// `max_decompressed_size` bytes (each stream is decoded against the
+ /// *remaining* budget, so N streams cannot sum to N times the limit), which
+ /// stops a small compressed page stream from inflating without limit when
+ /// processing untrusted PDFs. Use it (and
+ /// [`Document::extract_text_with_limit`]) instead of the unbounded variants
+ /// for input you do not control.
+ ///
+ /// Returns [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded)
+ /// if the page content would exceed the limit. Like
+ /// [`Document::get_page_content`], a stream that fails to decode for a reason
+ /// *other* than the size limit falls back to its raw bytes, but that fallback
+ /// is also kept within the remaining budget.
+ pub fn get_page_content_with_limit(&self, page_id: ObjectId, max_decompressed_size: usize) -> Result<Vec<u8>> {
+ let mut content = Vec::new();
+ let content_streams = self.get_page_contents(page_id);
+ for object_id in content_streams {
+ if let Ok(content_stream) = self.get_object(object_id).and_then(Object::as_stream) {
+ let remaining = max_decompressed_size.saturating_sub(content.len());
+ match content_stream.decompressed_content_with_limit(remaining) {
+ Ok(data) => content.extend_from_slice(&data),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { .. })) => {
+ return Err(DecompressError::MemoryLimitExceeded {
+ limit: max_decompressed_size,
+ }
+ .into());
+ }
+ // Mirror `get_page_content`'s lenient fallback to the raw
+ // (still-compressed) bytes when a stream can't be decoded, but
+ // keep that fallback within the page's remaining budget so a
+ // large raw stream can't bypass the guard.
+ Err(_) => {
+ if content_stream.content.len() > remaining {
+ return Err(DecompressError::MemoryLimitExceeded {
+ limit: max_decompressed_size,
+ }
+ .into());
+ }
+ content.extend_from_slice(&content_stream.content);
+ }
+ }
+ content.push(b'\n');
+ }
+ }
+ Ok(content)
+ }
+
+ /// Get resources used by a page.
+ pub fn get_page_resources(&self, page_id: ObjectId) -> Result<(Option<&Dictionary>, Vec<ObjectId>)> {
+ fn collect_resources(
+ page_node: &Dictionary, resource_ids: &mut Vec<ObjectId>, doc: &Document,
+ already_seen: &mut HashSet<ObjectId>,
+ ) -> Result<()> {
+ if let Ok(resource_id) = page_node.get(b"Resources").and_then(Object::as_reference) {
+ resource_ids.push(resource_id);
+ }
+ if let Ok(parent_id) = page_node.get(b"Parent").and_then(Object::as_reference) {
+ if already_seen.contains(&parent_id) {
+ return Err(Error::ReferenceCycle(parent_id));
+ }
+ if already_seen.len() >= crate::reader::MAX_NESTING_DEPTH {
+ return Err(Error::RecursionLimit);
+ }
+ already_seen.insert(parent_id);
+ let parent_dict = doc.get_dictionary(parent_id)?;
+ collect_resources(parent_dict, resource_ids, doc, already_seen)?;
+ }
+ Ok(())
+ }
+
+ let mut resource_dict = None;
+ let mut resource_ids = Vec::new();
+ if let Ok(page) = self.get_dictionary(page_id) {
+ resource_dict = page.get(b"Resources").and_then(Object::as_dict).ok();
+ collect_resources(page, &mut resource_ids, self, &mut HashSet::new())?;
+ }
+ Ok((resource_dict, resource_ids))
+ }
+
+ /// Get fonts used by a page.
+ pub fn get_page_fonts(&self, page_id: ObjectId) -> Result<BTreeMap<Vec<u8>, &Dictionary>> {
+ fn collect_fonts_from_resources<'a>(
+ resources: &'a Dictionary, fonts: &mut BTreeMap<Vec<u8>, &'a Dictionary>, doc: &'a Document,
+ ) {
+ if let Ok(font) = resources.get(b"Font") {
+ let font_dict = match font {
+ Object::Reference(id) => doc.get_object(*id).and_then(Object::as_dict).ok(),
+ Object::Dictionary(dict) => Some(dict),
+ _ => None,
+ };
+ if let Some(font_dict) = font_dict {
+ for (name, value) in font_dict.iter() {
+ let font = match value {
+ Object::Reference(id) => doc.get_dictionary(*id).ok(),
+ Object::Dictionary(dict) => Some(dict),
+ _ => None,
+ };
+ if !fonts.contains_key(name) {
+ font.map(|font| fonts.insert(name.clone(), font));
+ }
+ }
+ }
+ }
+ }
+
+ let mut fonts = BTreeMap::new();
+ let (resource_dict, resource_ids) = self.get_page_resources(page_id)?;
+ if let Some(resources) = resource_dict {
+ collect_fonts_from_resources(resources, &mut fonts, self);
+ }
+ for resource_id in resource_ids {
+ if let Ok(resources) = self.get_dictionary(resource_id) {
+ collect_fonts_from_resources(resources, &mut fonts, self);
+ }
+ }
+ Ok(fonts)
+ }
+
+ /// Get the PDF annotations of a page. The /Subtype of each annotation dictionary defines the
+ /// annotation type (Text, Link, Highlight, Underline, Ink, Popup, Widget, etc.). The /Rect of
+ /// an annotation dictionary defines its location on the page.
+ ///
+ /// `/Annots` itself may be an array or a reference to one, and each entry of that array may be
+ /// a reference to an annotation dictionary or, equally legally, the dictionary written directly
+ /// (ISO 32000-1, 12.5.2 requires an indirect object only for an annotation that carries a
+ /// `/Popup` or is the target of an `/IRT` reply). Both forms are returned.
+ ///
+ /// An entry that is neither is skipped, as is a reference that does not resolve to a
+ /// dictionary: a damaged entry costs its own annotation rather than the whole page.
+ pub fn get_page_annotations(&self, page_id: ObjectId) -> Result<Vec<&Dictionary>> {
+ let Ok(page) = self.get_dictionary(page_id) else {
+ return Ok(vec![]);
+ };
+ let entries = match page.get(b"Annots") {
+ Ok(Object::Reference(id)) => self.get_object(*id).and_then(Object::as_array)?,
+ Ok(Object::Array(entries)) => entries,
+ _ => return Ok(vec![]),
+ };
+ let mut annotations = Vec::with_capacity(entries.len());
+ for entry in entries {
+ match entry {
+ Object::Reference(id) => {
+ if let Ok(dictionary) = self.get_dictionary(*id) {
+ annotations.push(dictionary);
+ }
+ }
+ Object::Dictionary(dictionary) => annotations.push(dictionary),
+ _ => {}
+ }
+ }
+ Ok(annotations)
+ }
+
+ pub fn get_page_images(&'_ self, page_id: ObjectId) -> Result<Vec<PdfImage<'_>>> {
+ let mut images = vec![];
+ if let Ok(page) = self.get_dictionary(page_id) {
+ let resources = self.get_dict_in_dict(page, b"Resources")?;
+ let xobject = match self.get_dict_in_dict(resources, b"XObject") {
+ Ok(xobject) => xobject,
+ Err(err) => match err {
+ // XObject is optional, no images found
+ Error::DictKey(_) => return Ok(Vec::default()),
+ _ => Err(err)?,
+ },
+ };
+
+ for (_, xvalue) in xobject.iter() {
+ let id = xvalue.as_reference()?;
+ let xvalue = self.get_object(id)?;
+ let xvalue = xvalue.as_stream()?;
+ let dict = &xvalue.dict;
+ if dict.get(b"Subtype")?.as_name()? != b"Image" {
+ continue;
+ }
+ let width = dict.get(b"Width")?.as_i64()?;
+ let height = dict.get(b"Height")?.as_i64()?;
+ let color_space = match dict.get(b"ColorSpace") {
+ Ok(cs) => match cs {
+ Object::Array(array) => match array.first() {
+ Some(first) => Some(String::from_utf8_lossy(first.as_name()?).to_string()),
+ None => None,
+ },
+ Object::Name(name) => Some(String::from_utf8_lossy(name).to_string()),
+ _ => None,
+ },
+ Err(_) => None,
+ };
+ let bits_per_component = match dict.get(b"BitsPerComponent") {
+ Ok(bpc) => Some(bpc.as_i64()?),
+ Err(_) => None,
+ };
+ let mut filters = vec![];
+ if let Ok(filter) = dict.get(b"Filter") {
+ match filter {
+ Object::Array(array) => {
+ for obj in array.iter() {
+ let name = obj.as_name()?;
+ filters.push(String::from_utf8_lossy(name).to_string());
+ }
+ }
+ Object::Name(name) => {
+ filters.push(String::from_utf8_lossy(name).to_string());
+ }
+ _ => {}
+ }
+ };
+
+ images.push(PdfImage {
+ id,
+ width,
+ height,
+ color_space,
+ bits_per_component,
+ filters: Some(filters),
+ content: &xvalue.content,
+ origin_dict: &xvalue.dict,
+ });
+ }
+ }
+ Ok(images)
+ }
+
+ pub fn decode_text(encoding: &Encoding, bytes: &[u8]) -> Result<String> {
+ debug!("Decoding text with {encoding:#?}");
+ encoding.bytes_to_string(bytes)
+ }
+
+ pub fn encode_text(encoding: &Encoding, text: &str) -> Vec<u8> {
+ encoding.string_to_bytes(text)
+ }
+}
+
+impl Default for Document {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+struct PageTreeIter<'a> {
+ doc: &'a Document,
+ stack: Vec<&'a [Object]>,
+ kids: Option<&'a [Object]>,
+ iter_limit: usize,
+}
+
+impl<'a> PageTreeIter<'a> {
+ const PAGE_TREE_DEPTH_LIMIT: usize = 256;
+
+ fn new(doc: &'a Document) -> Self {
+ if let Ok(page_tree_id) = doc
+ .catalog()
+ .and_then(|cat| cat.get(b"Pages"))
+ .and_then(Object::as_reference)
+ {
+ Self {
+ doc,
+ kids: Self::kids(doc, page_tree_id),
+ stack: Vec::with_capacity(32),
+ iter_limit: doc.objects.len(),
+ }
+ } else {
+ Self {
+ doc,
+ kids: None,
+ stack: Vec::new(),
+ iter_limit: doc.objects.len(),
+ }
+ }
+ }
+
+ fn kids(doc: &Document, page_tree_id: ObjectId) -> Option<&[Object]> {
+ doc.get_dictionary(page_tree_id)
+ .and_then(|page_tree| page_tree.get_deref(b"Kids", doc))
+ .and_then(Object::as_array)
+ .map(|k| k.as_slice())
+ .ok()
+ }
+}
+
+impl Iterator for PageTreeIter<'_> {
+ type Item = ObjectId;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ loop {
+ while let Some((kid, new_kids)) = self.kids.and_then(|k| k.split_first()) {
+ if self.iter_limit == 0 {
+ return None;
+ }
+ self.iter_limit -= 1;
+
+ self.kids = Some(new_kids);
+
+ if let Ok(kid_id) = kid.as_reference()
+ && let Ok(type_name) = self.doc.get_dictionary(kid_id).and_then(Dictionary::get_type)
+ {
+ match type_name {
+ b"Page" => {
+ return Some(kid_id);
+ }
+ b"Pages" if self.stack.len() < Self::PAGE_TREE_DEPTH_LIMIT => {
+ let kids = self.kids.unwrap();
+ if !kids.is_empty() {
+ self.stack.push(kids);
+ }
+ self.kids = Self::kids(self.doc, kid_id);
+ }
+ b"Pages" => {}
+ _ => {}
+ }
+ }
+ }
+
+ // Current level exhausted, try to pop.
+ if let kids @ Some(_) = self.stack.pop() {
+ self.kids = kids;
+ } else {
+ return None;
+ }
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let kids = self.kids.unwrap_or(&[]);
+
+ let nb_pages: usize = kids
+ .iter()
+ .chain(self.stack.iter().flat_map(|k| k.iter()))
+ .map(|kid| {
+ if let Ok(dict) = kid.as_reference().and_then(|id| self.doc.get_dictionary(id)) {
+ if let Ok(b"Pages") = dict.get_type() {
+ let count = dict.get_deref(b"Count", self.doc).and_then(Object::as_i64).unwrap_or(0);
+ // Don't let page count go backwards in case of an invalid document.
+ max(0, count) as usize
+ } else {
+ 1
+ }
+ } else {
+ 1
+ }
+ })
+ .sum();
+
+ (nb_pages, Some(nb_pages))
+ }
+}
+
+impl std::iter::FusedIterator for PageTreeIter<'_> {}
diff --git a/vendor/lopdf/src/encodings/cmap.rs b/vendor/lopdf/src/encodings/cmap.rs
new file mode 100644
index 000000000..0729a54b7
--- /dev/null
+++ b/vendor/lopdf/src/encodings/cmap.rs
@@ -0,0 +1,281 @@
+use crate::cmap_section::{CMapParseError, CMapSection, CodeLen, SourceCode};
+use crate::parser::cmap_parser::parse;
+
+use log::error;
+use rangemap::RangeInclusiveMap;
+use std::collections::HashMap;
+use thiserror::Error;
+
+/// Unicode Cmap is implemented by 4 maps.
+/// Each map contains a mappings from source codes to unicode values for a different length of codes.
+/// Codes vary from 1 byte to 4 bytes so they are always in limits of u32.
+/// However to map a code to a unicode value an additional knowledge about the number of bytes is needed,
+/// as 2 byte code <0000> shouldn't be matched with a single byte <00> even though they have the same integer value.
+#[derive(Debug, Default)]
+pub struct ToUnicodeCMap {
+ pub bf_ranges: [RangeInclusiveMap<SourceCode, BfRangeTarget>; 4],
+ reverse_map: Option<HashMap<Vec<u16>, Vec<ReverseCMapEntry>>>,
+}
+/// Represents the information needed to map a Unicode sequence back to a source code.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ReverseCMapEntry {
+ pub source_code: SourceCode,
+ pub code_len: CodeLen,
+ // Optionally, add priority if multiple source codes map to the same Unicode sequence
+ // pub priority: u8,
+}
+
+#[derive(Debug, Error)]
+pub enum UnicodeCMapError {
+ #[error("could not parse ToUnicode CMap: {0:#?}")]
+ Parse(CMapParseError),
+ #[error("invalid code range")]
+ InvalidCodeRange,
+}
+
+impl From<CMapParseError> for UnicodeCMapError {
+ fn from(err: CMapParseError) -> Self {
+ UnicodeCMapError::Parse(err)
+ }
+}
+
+impl ToUnicodeCMap {
+ const REPLACEMENT_CHAR: u16 = 0xfffd;
+
+ pub fn new() -> ToUnicodeCMap {
+ ToUnicodeCMap {
+ bf_ranges: [(); 4].map(|_| RangeInclusiveMap::new()),
+ reverse_map: None,
+ }
+ }
+
+ pub(crate) fn parse(stream_content: Vec<u8>) -> Result<ToUnicodeCMap, UnicodeCMapError> {
+ let cmap_sections = parse(&stream_content[..])?;
+ Self::from_sections(cmap_sections)
+ }
+
+ fn from_sections(cmap_sections: Vec<CMapSection>) -> Result<ToUnicodeCMap, UnicodeCMapError> {
+ let mut cmap = Self::new();
+ for section in cmap_sections {
+ match section {
+ CMapSection::CsRange(_) => (), // currently no additional validation is implemented for code ranges
+ CMapSection::BfChar(char_mappings) => {
+ for ((code, code_len), dst) in char_mappings {
+ cmap.put_char(code, code_len, dst);
+ }
+ }
+ CMapSection::BfRange(range_mappings) => {
+ for ((start, end, code_len), dst_vec) in range_mappings {
+ if end < start {
+ return Err(UnicodeCMapError::InvalidCodeRange);
+ }
+ match dst_vec.len() {
+ 1 if dst_vec[0].len() == 1 => cmap.put(
+ start,
+ end,
+ code_len,
+ BfRangeTarget::UTF16CodePoint {
+ offset: u32::wrapping_sub(dst_vec[0][0] as u32, start),
+ },
+ ),
+ 1 => cmap.put(start, end, code_len, BfRangeTarget::HexString(dst_vec[0].clone())),
+ 0 => return Err(UnicodeCMapError::InvalidCodeRange),
+ _ => cmap.put(start, end, code_len, BfRangeTarget::ArrayOfHexStrings(dst_vec.clone())),
+ }
+ }
+ }
+ }
+ }
+
+ let mut rev_map = HashMap::new();
+
+ for code_len_idx in 0..cmap.bf_ranges.len() {
+ let code_len = (code_len_idx + 1) as u8;
+ for (range, target) in cmap.bf_ranges[code_len_idx].iter() {
+ for src_code in range.clone() {
+ let unicode_sequence: Option<Vec<u16>> = match target {
+ BfRangeTarget::UTF16CodePoint { offset } => {
+ Some(vec![u32::wrapping_add(src_code, *offset) as u16])
+ }
+ BfRangeTarget::HexString(hex_str_vec) => {
+ // If the hex_str_vec itself is the target for a single src_code in a bfchar-like mapping
+ // or if it's a base for a bfrange where only the last element increments.
+ if src_code == *range.start() {
+ // Simplified: assume direct mapping for start of range
+ Some(hex_str_vec.clone())
+ } else if hex_str_vec.len() == 1 {
+ // For ranges like <01> <05> <0041>
+ Some(vec![hex_str_vec[0].wrapping_add((src_code - range.start()) as u16)])
+ } else if !hex_str_vec.is_empty() {
+ // For ranges like <01> <05> [<0041> <0042> ...]
+ let mut current_hex_str = hex_str_vec.clone();
+ if let Some(last_val) = current_hex_str.last_mut() {
+ *last_val = last_val.wrapping_add((src_code - range.start()) as u16);
+ Some(current_hex_str)
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ }
+ BfRangeTarget::ArrayOfHexStrings(array_of_hex_str) => {
+ let index = (src_code - range.start()) as usize;
+ if index < array_of_hex_str.len() {
+ Some(array_of_hex_str[index].clone())
+ } else {
+ None
+ }
+ }
+ };
+
+ if let Some(uni_seq) = unicode_sequence
+ && !uni_seq.is_empty()
+ {
+ rev_map.entry(uni_seq).or_insert_with(Vec::new).push(ReverseCMapEntry {
+ source_code: src_code,
+ code_len,
+ });
+ }
+ }
+ }
+ }
+ cmap.reverse_map = Some(rev_map);
+
+ Ok(cmap)
+ }
+
+ pub fn get(&self, code: SourceCode, code_len: CodeLen) -> Option<Vec<u16>> {
+ if code_len > 4 || code_len == 0 {
+ error!("Code lenght should be between l and 4 bytes, got {code_len}");
+ return None;
+ }
+ use BfRangeTarget::*;
+
+ let bf_ranges_map = &self.bf_ranges[(code_len - 1) as usize];
+
+ bf_ranges_map.get_key_value(&code).map(|(range, value)| match value {
+ HexString(vec) => {
+ let mut ret_vec = vec.clone();
+ *(ret_vec.last_mut().unwrap()) += (code - range.start()) as u16;
+ ret_vec
+ }
+ UTF16CodePoint { offset } => vec![u32::wrapping_add(code, *offset) as u16],
+ ArrayOfHexStrings(vec_of_strings) => {
+ let idx = (code - range.start()) as usize;
+ if idx < vec_of_strings.len() {
+ vec_of_strings[idx].clone()
+ } else {
+ vec![ToUnicodeCMap::REPLACEMENT_CHAR]
+ }
+ }
+ })
+ }
+
+ pub fn get_or_replacement_char(&self, code: SourceCode, code_len: CodeLen) -> Vec<u16> {
+ self.get(code, code_len)
+ .unwrap_or(vec![ToUnicodeCMap::REPLACEMENT_CHAR])
+ }
+
+ pub fn put(&mut self, src_code_lo: SourceCode, src_code_hi: SourceCode, code_len: CodeLen, target: BfRangeTarget) {
+ if code_len > 4 || code_len == 0 {
+ error!("Code lenght should be between l and 4 bytes, got {code_len}, ignoring");
+ return;
+ }
+ self.bf_ranges[(code_len - 1) as usize].insert(src_code_lo..=src_code_hi, target)
+ }
+
+ pub fn put_char(&mut self, code: SourceCode, code_len: CodeLen, dst: Vec<u16>) {
+ let target = if dst.len() == 1 {
+ BfRangeTarget::UTF16CodePoint {
+ offset: u32::wrapping_sub(dst[0] as u32, code),
+ }
+ } else {
+ BfRangeTarget::HexString(dst)
+ };
+ self.put(code, code, code_len, target)
+ }
+
+ /// Gets the source code(s) for a given Unicode sequence.
+ /// Prioritizes shorter byte sequences if multiple mappings exist.
+ pub fn get_source_codes_for_unicode(&self, unicode_sequence: &[u16]) -> Option<&[ReverseCMapEntry]> {
+ if let Some(map) = &self.reverse_map {
+ // TODO: Add prioritization logic if needed (e.g., prefer shorter code_len)
+ map.get(unicode_sequence).map(|v| v.as_slice())
+ } else {
+ None
+ }
+ }
+}
+
+#[derive(Debug, PartialEq, Eq, Clone)]
+pub enum BfRangeTarget {
+ // UTF16-BE encoding is used
+ HexString(Vec<u16>),
+ // don't store the actual codepoint but rather an offset to the src_code_lo
+ // so that consecutive ranges can be mapped to the same value in the range map
+ UTF16CodePoint { offset: u32 },
+ ArrayOfHexStrings(Vec<Vec<u16>>),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn put_char_can_be_retrieved() {
+ let mut cmap = ToUnicodeCMap::new();
+ let char_code = 0x01;
+ let char_value = vec![0x1234];
+ cmap.put_char(char_code, 2, char_value.clone());
+
+ assert_eq!(cmap.get(char_code, 2), Some(char_value))
+ }
+
+ #[test]
+ fn char_can_be_retrieved_only_by_appropriate_len() {
+ let mut cmap = ToUnicodeCMap::new();
+ let char_code = 0x1;
+ let code_len = 4;
+ let char_value = vec![0x1234];
+ cmap.put_char(char_code, code_len, char_value.clone());
+
+ for i in 1..=3 {
+ assert_eq!(cmap.get(char_code, i), None);
+ }
+
+ assert_eq!(cmap.get(char_code, code_len), Some(char_value));
+ }
+
+ #[test]
+ fn wrong_code_len_does_not_panic() {
+ let mut cmap = ToUnicodeCMap::new();
+ let char_code = 0x1;
+ let char_value = vec![0x1234];
+
+ cmap.put_char(char_code, 5, char_value.clone());
+ cmap.put_char(char_code, 0, char_value.clone());
+ }
+
+ #[test]
+ fn array_of_hex_strings_out_of_bounds_returns_replacement() {
+ // Simulate a malformed CMap bfrange where the array has fewer entries
+ // than the declared source code range covers.
+ let mut cmap = ToUnicodeCMap::new();
+ let array = BfRangeTarget::ArrayOfHexStrings(vec![
+ vec![0x0041], // 'A' — for code 0x10
+ vec![0x0042], // 'B' — for code 0x11
+ ]);
+ // Range 0x10..=0x14 but only 2 entries in array (needs 5)
+ cmap.put(0x10, 0x14, 2, array);
+
+ // In-bounds lookups work
+ assert_eq!(cmap.get(0x10, 2), Some(vec![0x0041]));
+ assert_eq!(cmap.get(0x11, 2), Some(vec![0x0042]));
+
+ // Out-of-bounds lookups return replacement char instead of panicking
+ assert_eq!(cmap.get(0x12, 2), Some(vec![ToUnicodeCMap::REPLACEMENT_CHAR]));
+ assert_eq!(cmap.get(0x13, 2), Some(vec![ToUnicodeCMap::REPLACEMENT_CHAR]));
+ assert_eq!(cmap.get(0x14, 2), Some(vec![ToUnicodeCMap::REPLACEMENT_CHAR]));
+ }
+}
diff --git a/vendor/lopdf/src/encodings/differences.rs b/vendor/lopdf/src/encodings/differences.rs
new file mode 100644
index 000000000..99c3c1b88
--- /dev/null
+++ b/vendor/lopdf/src/encodings/differences.rs
@@ -0,0 +1,48 @@
+use super::{Encoding, Glyph, Result};
+use indexmap::IndexMap;
+
+pub struct Differences<'a> {
+ pub base: Box<Encoding<'a>>,
+ pub map: IndexMap<u8, Glyph>,
+ pub inverse: IndexMap<Glyph, u8>,
+}
+
+impl Differences<'_> {
+ pub(super) fn bytes_to_string(&self, bytes: &[u8], out: &mut String) -> Result<()> {
+ for byte in bytes {
+ let Some(glyph) = self.map.get(byte) else {
+ self.base.write_to_string(&[*byte], out)?;
+ continue;
+ };
+
+ for c in char::decode_utf16([glyph.utf16_code_unit()]).flatten() {
+ out.push_str(c.encode_utf8(&mut [0; 4]));
+ }
+ }
+
+ Ok(())
+ }
+
+ pub(super) fn string_to_bytes(&self, text: &str, out: &mut Vec<u8>) {
+ for c in text.chars() {
+ let mut any = false;
+
+ for code_unit in c.encode_utf16(&mut [0; 2]) {
+ let glyph = Glyph::from_utf16_code_unit(*code_unit);
+
+ if let Some(byte) = self.inverse.get(&glyph) {
+ out.push(*byte);
+ any = true;
+ }
+ }
+
+ if any {
+ continue;
+ }
+
+ let mut b = [0; 4];
+ let s = c.encode_utf8(&mut b);
+ self.base.write_to_bytes(s, out);
+ }
+ }
+}
diff --git a/vendor/lopdf/src/encodings/glyphnames.rs b/vendor/lopdf/src/encodings/glyphnames.rs
new file mode 100644
index 000000000..a0200e171
--- /dev/null
+++ b/vendor/lopdf/src/encodings/glyphnames.rs
@@ -0,0 +1,3803 @@
+use core::fmt;
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[repr(transparent)]
+pub struct Glyph(u16);
+
+impl Glyph {
+ /// Construct a glyph from a UTF-16 code unit.
+ #[inline]
+ pub fn from_utf16_code_unit(c: u16) -> Self {
+ Self(c)
+ }
+
+ /// Returns the UTF-16 code unit associated with this glyph.
+ #[inline]
+ pub fn utf16_code_unit(&self) -> u16 {
+ self.0
+ }
+}
+
+macro_rules! glyphs {
+ (
+ $(
+ $code:literal = [$first:ident $(, $rest:ident)*];
+ )*
+ ) => {
+ #[allow(dead_code)]
+ #[allow(non_upper_case_globals)]
+ impl Glyph {
+ $(
+ pub const $first: Glyph = Glyph($code);
+ $(pub const $rest: Glyph = Glyph($code);)*
+ )*
+
+ pub fn from_name(name: &[u8]) -> Option<Self> {
+ // This part is a bit of a hack, since we don't have a nice way
+ // of getting a byte string literal. But, as_bytes is const
+ // since 1.32.
+ $(
+ const $first: &[u8] = stringify!($first).as_bytes();
+ $(const $rest: &[u8] = stringify!($rest).as_bytes();)*
+ )*
+
+ match name {
+ $(
+ $first => Some(Self::$first),
+ $($rest => Some(Self::$rest),)*
+ )*
+ _ => None,
+ }
+ }
+ }
+
+ impl fmt::Debug for Glyph {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Glyph(0x{:04x})", self.0)
+ }
+ }
+
+ #[repr(u16)]
+ #[allow(non_camel_case_types)]
+ enum _Reject {
+ $($first = $code,)*
+ }
+ }
+}
+
+glyphs! {
+ 0x0001 = [controlSTX];
+ 0x0002 = [controlSOT];
+ 0x0003 = [controlETX];
+ 0x0004 = [controlEOT];
+ 0x0005 = [controlENQ];
+ 0x0006 = [controlACK];
+ 0x0007 = [controlBEL];
+ 0x0008 = [controlBS];
+ 0x0009 = [controlHT];
+ 0x000a = [controlLF];
+ 0x000b = [controlVT];
+ 0x000c = [controlFF];
+ 0x000d = [controlCR];
+ 0x000e = [controlSO];
+ 0x000f = [controlSI];
+ 0x0010 = [controlDLE];
+ 0x0011 = [controlDC1];
+ 0x0012 = [controlDC2];
+ 0x0013 = [controlDC3];
+ 0x0014 = [controlDC4];
+ 0x0015 = [controlNAK];
+ 0x0016 = [controlSYN];
+ 0x0017 = [controlETB];
+ 0x0018 = [controlCAN];
+ 0x0019 = [controlEM];
+ 0x001a = [controlSUB];
+ 0x001b = [controlESC];
+ 0x001c = [controlFS];
+ 0x001d = [controlGS];
+ 0x001e = [controlRS];
+ 0x001f = [controlUS];
+ 0x0020 = [space, spacehackarabic];
+ 0x0021 = [exclam];
+ 0x0022 = [quotedbl];
+ 0x0023 = [numbersign];
+ 0x0024 = [dollar];
+ 0x0025 = [percent];
+ 0x0026 = [ampersand];
+ 0x0027 = [quotesingle];
+ 0x0028 = [parenleft, parenleftbig, parenleftBig, parenleftbigg, parenleftBigg];
+ 0x0029 = [parenright, parenrightbig, parenrightBig, parenrightbigg, parenrightBigg];
+ 0x002a = [asterisk];
+ 0x002b = [plus];
+ 0x002c = [comma];
+ 0x002d = [hyphen, hyphenchar];
+ 0x002e = [period];
+ 0x002f = [slash];
+ 0x0030 = [zero];
+ 0x0031 = [one];
+ 0x0032 = [two];
+ 0x0033 = [three];
+ 0x0034 = [four];
+ 0x0035 = [five];
+ 0x0036 = [six];
+ 0x0037 = [seven];
+ 0x0038 = [eight];
+ 0x0039 = [nine];
+ 0x003a = [colon];
+ 0x003b = [semicolon];
+ 0x003c = [less];
+ 0x003d = [equal];
+ 0x003e = [greater];
+ 0x003f = [question];
+ 0x0040 = [at];
+ 0x0041 = [A];
+ 0x0042 = [B];
+ 0x0043 = [C];
+ 0x0044 = [D];
+ 0x0045 = [E];
+ 0x0046 = [F];
+ 0x0047 = [G];
+ 0x0048 = [H];
+ 0x0049 = [I];
+ 0x004a = [J];
+ 0x004b = [K];
+ 0x004c = [L];
+ 0x004d = [M];
+ 0x004e = [N];
+ 0x004f = [O];
+ 0x0050 = [P];
+ 0x0051 = [Q];
+ 0x0052 = [R];
+ 0x0053 = [Germandbls, S, SS];
+ 0x0054 = [T];
+ 0x0055 = [U];
+ 0x0056 = [V];
+ 0x0057 = [W];
+ 0x0058 = [X];
+ 0x0059 = [Y];
+ 0x005a = [Z];
+ 0x005b = [bracketleft, bracketleftbig, bracketleftBig, bracketleftbigg, bracketleftBigg];
+ 0x005c = [backslash, backslashbig, backslashBig, backslashbigg, backslashBigg];
+ 0x005d = [bracketright, bracketrightbig, bracketrightBig, bracketrightbigg, bracketrightBigg];
+ 0x005e = [asciicircum];
+ 0x005f = [underscore];
+ 0x0060 = [grave];
+ 0x0061 = [a];
+ 0x0062 = [b];
+ 0x0063 = [c];
+ 0x0064 = [d];
+ 0x0065 = [e];
+ 0x0066 = [f];
+ 0x0067 = [g];
+ 0x0068 = [h];
+ 0x0069 = [i];
+ 0x006a = [j];
+ 0x006b = [k];
+ 0x006c = [l];
+ 0x006d = [m];
+ 0x006e = [n];
+ 0x006f = [o];
+ 0x0070 = [p];
+ 0x0071 = [q];
+ 0x0072 = [r];
+ 0x0073 = [s];
+ 0x0074 = [t];
+ 0x0075 = [u];
+ 0x0076 = [v];
+ 0x0077 = [w];
+ 0x0078 = [x];
+ 0x0079 = [y];
+ 0x007a = [z];
+ 0x007b = [braceleft, braceleftbig, braceleftBig, braceleftbigg, braceleftBigg];
+ 0x007c = [bar, barex, braceex, braceleftmid, parenleftex, parenrightex, verticalbar];
+ 0x007d = [braceright, bracerightbig, bracerightBig, bracerightbigg, bracerightBigg];
+ 0x007e = [asciitilde];
+ 0x007f = [controlDEL];
+ 0x00a0 = [nbspace, nonbreakingspace];
+ 0x00a1 = [exclamdown];
+ 0x00a2 = [cent];
+ 0x00a3 = [sterling];
+ 0x00a4 = [currency];
+ 0x00a5 = [yen];
+ 0x00a6 = [brokenbar];
+ 0x00a7 = [section];
+ 0x00a8 = [dieresis];
+ 0x00a9 = [copyright];
+ 0x00aa = [ordfeminine];
+ 0x00ab = [guillemotleft];
+ 0x00ac = [logicalnot];
+ 0x00ad = [sfthyphen, softhyphen];
+ 0x00ae = [registered];
+ 0x00af = [macron, overscore];
+ 0x00b0 = [degree];
+ 0x00b1 = [plusminus];
+ 0x00b2 = [twosuperior];
+ 0x00b3 = [threesuperior];
+ 0x00b4 = [acute];
+ 0x00b5 = [mu, mu1];
+ 0x00b6 = [paragraph];
+ 0x00b7 = [middot, periodcentered];
+ 0x00b8 = [cedilla];
+ 0x00b9 = [onesuperior];
+ 0x00ba = [ordmasculine];
+ 0x00bb = [guillemotright];
+ 0x00bc = [onequarter];
+ 0x00bd = [onehalf];
+ 0x00be = [threequarters];
+ 0x00bf = [questiondown];
+ 0x00c0 = [Agrave];
+ 0x00c1 = [Aacute];
+ 0x00c2 = [Acircumflex];
+ 0x00c3 = [Atilde];
+ 0x00c4 = [Adieresis];
+ 0x00c5 = [Aring];
+ 0x00c6 = [AE];
+ 0x00c7 = [Ccedilla];
+ 0x00c8 = [Egrave];
+ 0x00c9 = [Eacute];
+ 0x00ca = [Ecircumflex];
+ 0x00cb = [Edieresis];
+ 0x00cc = [Igrave];
+ 0x00cd = [Iacute];
+ 0x00ce = [Icircumflex];
+ 0x00cf = [Idieresis];
+ 0x00d0 = [Eth];
+ 0x00d1 = [Ntilde];
+ 0x00d2 = [Ograve];
+ 0x00d3 = [Oacute];
+ 0x00d4 = [Ocircumflex];
+ 0x00d5 = [Otilde];
+ 0x00d6 = [Odieresis];
+ 0x00d7 = [multiply];
+ 0x00d8 = [Oslash];
+ 0x00d9 = [Ugrave];
+ 0x00da = [Uacute];
+ 0x00db = [Ucircumflex];
+ 0x00dc = [Udieresis];
+ 0x00dd = [Yacute];
+ 0x00de = [Thorn];
+ 0x00df = [germandbls];
+ 0x00e0 = [agrave];
+ 0x00e1 = [aacute];
+ 0x00e2 = [acircumflex];
+ 0x00e3 = [atilde];
+ 0x00e4 = [adieresis];
+ 0x00e5 = [aring];
+ 0x00e6 = [ae];
+ 0x00e7 = [ccedilla];
+ 0x00e8 = [egrave];
+ 0x00e9 = [eacute];
+ 0x00ea = [ecircumflex];
+ 0x00eb = [edieresis];
+ 0x00ec = [igrave];
+ 0x00ed = [iacute];
+ 0x00ee = [icircumflex];
+ 0x00ef = [idieresis];
+ 0x00f0 = [eth];
+ 0x00f1 = [ntilde];
+ 0x00f2 = [ograve];
+ 0x00f3 = [oacute];
+ 0x00f4 = [ocircumflex];
+ 0x00f5 = [otilde];
+ 0x00f6 = [odieresis];
+ 0x00f7 = [divide];
+ 0x00f8 = [oslash];
+ 0x00f9 = [ugrave];
+ 0x00fa = [uacute];
+ 0x00fb = [ucircumflex];
+ 0x00fc = [udieresis];
+ 0x00fd = [yacute];
+ 0x00fe = [thorn];
+ 0x00ff = [ydieresis];
+ 0x0100 = [Amacron];
+ 0x0101 = [amacron];
+ 0x0102 = [Abreve];
+ 0x0103 = [abreve];
+ 0x0104 = [Aogonek];
+ 0x0105 = [aogonek];
+ 0x0106 = [Cacute];
+ 0x0107 = [cacute];
+ 0x0108 = [Ccircumflex];
+ 0x0109 = [ccircumflex];
+ 0x010a = [Cdot, Cdotaccent];
+ 0x010b = [cdot, cdotaccent];
+ 0x010c = [Ccaron];
+ 0x010d = [ccaron];
+ 0x010e = [Dcaron];
+ 0x010f = [dcaron];
+ 0x0110 = [Dbar, Dcroat, Dslash];
+ 0x0111 = [dbar, dcroat, dmacron];
+ 0x0112 = [Emacron];
+ 0x0113 = [emacron];
+ 0x0114 = [Ebreve];
+ 0x0115 = [ebreve];
+ 0x0116 = [Edot, Edotaccent];
+ 0x0117 = [edot, edotaccent];
+ 0x0118 = [Eogonek];
+ 0x0119 = [eogonek];
+ 0x011a = [Ecaron];
+ 0x011b = [ecaron];
+ 0x011c = [Gcircumflex];
+ 0x011d = [gcircumflex];
+ 0x011e = [Gbreve];
+ 0x011f = [gbreve];
+ 0x0120 = [Gdot, Gdotaccent];
+ 0x0121 = [gdot, gdotaccent];
+ 0x0122 = [Gcedilla, Gcommaaccent];
+ 0x0123 = [gcedilla, gcommaaccent];
+ 0x0124 = [Hcircumflex];
+ 0x0125 = [hcircumflex];
+ 0x0126 = [Hbar];
+ 0x0127 = [hbar];
+ 0x0128 = [Itilde];
+ 0x0129 = [itilde];
+ 0x012a = [Imacron];
+ 0x012b = [imacron];
+ 0x012c = [Ibreve];
+ 0x012d = [ibreve];
+ 0x012e = [Iogonek];
+ 0x012f = [iogonek];
+ 0x0130 = [Idot, Idotaccent];
+ 0x0131 = [dotlessi];
+ 0x0132 = [IJ];
+ 0x0133 = [ij];
+ 0x0134 = [Jcircumflex];
+ 0x0135 = [jcircumflex];
+ 0x0136 = [Kcedilla, Kcommaaccent];
+ 0x0137 = [kcedilla, kcommaaccent];
+ 0x0138 = [kgreenlandic];
+ 0x0139 = [Lacute];
+ 0x013a = [lacute];
+ 0x013b = [Lcedilla, Lcommaaccent];
+ 0x013c = [lcedilla, lcommaaccent];
+ 0x013d = [Lcaron];
+ 0x013e = [lcaron];
+ 0x013f = [Ldot, Ldotaccent];
+ 0x0140 = [ldot, ldotaccent];
+ 0x0141 = [Lslash];
+ 0x0142 = [lslash];
+ 0x0143 = [Nacute];
+ 0x0144 = [nacute];
+ 0x0145 = [Ncedilla, Ncommaaccent];
+ 0x0146 = [ncedilla, ncommaaccent];
+ 0x0147 = [Ncaron];
+ 0x0148 = [ncaron];
+ 0x0149 = [napostrophe, quoterightn];
+ 0x014a = [Eng, Ng];
+ 0x014b = [eng, ng];
+ 0x014c = [Omacron];
+ 0x014d = [omacron];
+ 0x014e = [Obreve];
+ 0x014f = [obreve];
+ 0x0150 = [Odblacute, Ohungarumlaut];
+ 0x0151 = [odblacute, ohungarumlaut];
+ 0x0152 = [OE];
+ 0x0153 = [oe];
+ 0x0154 = [Racute];
+ 0x0155 = [racute];
+ 0x0156 = [Rcedilla, Rcommaaccent];
+ 0x0157 = [rcedilla, rcommaaccent];
+ 0x0158 = [Rcaron];
+ 0x0159 = [rcaron];
+ 0x015a = [Sacute];
+ 0x015b = [sacute];
+ 0x015c = [Scircumflex];
+ 0x015d = [scircumflex];
+ 0x015e = [Scedilla];
+ 0x015f = [scedilla];
+ 0x0160 = [Scaron];
+ 0x0161 = [scaron];
+ 0x0162 = [Tcedilla, Tcommaaccent];
+ 0x0163 = [tcedilla, tcommaaccent];
+ 0x0164 = [Tcaron];
+ 0x0165 = [tcaron];
+ 0x0166 = [Tbar];
+ 0x0167 = [tbar];
+ 0x0168 = [Utilde];
+ 0x0169 = [utilde];
+ 0x016a = [Umacron];
+ 0x016b = [umacron];
+ 0x016c = [Ubreve];
+ 0x016d = [ubreve];
+ 0x016e = [Uring];
+ 0x016f = [uring];
+ 0x0170 = [Udblacute, Uhungarumlaut];
+ 0x0171 = [udblacute, uhungarumlaut];
+ 0x0172 = [Uogonek];
+ 0x0173 = [uogonek];
+ 0x0174 = [Wcircumflex];
+ 0x0175 = [wcircumflex];
+ 0x0176 = [Ycircumflex];
+ 0x0177 = [ycircumflex];
+ 0x0178 = [Ydieresis];
+ 0x0179 = [Zacute];
+ 0x017a = [zacute];
+ 0x017b = [Zdot, Zdotaccent];
+ 0x017c = [zdot, zdotaccent];
+ 0x017d = [Zcaron];
+ 0x017e = [zcaron];
+ 0x017f = [longs, slong];
+ 0x0180 = [bstroke];
+ 0x0181 = [Bhook];
+ 0x0182 = [Btopbar];
+ 0x0183 = [btopbar];
+ 0x0184 = [Tonesix];
+ 0x0185 = [tonesix];
+ 0x0186 = [Oopen];
+ 0x0187 = [Chook];
+ 0x0188 = [chook];
+ 0x0189 = [Dafrican];
+ 0x018a = [Dhook];
+ 0x018b = [Dtopbar];
+ 0x018c = [dtopbar];
+ 0x018d = [deltaturned];
+ 0x018e = [Ereversed];
+ 0x018f = [Schwa];
+ 0x0190 = [Eopen];
+ 0x0191 = [Fhook];
+ 0x0192 = [florin];
+ 0x0193 = [Ghook];
+ 0x0194 = [Gammaafrican];
+ 0x0195 = [hv];
+ 0x0196 = [Iotaafrican];
+ 0x0197 = [Istroke];
+ 0x0198 = [Khook];
+ 0x0199 = [khook];
+ 0x019a = [lbar];
+ 0x019b = [lambdastroke];
+ 0x019c = [Mturned];
+ 0x019d = [Nhookleft];
+ 0x019e = [nlegrightlong];
+ 0x019f = [Ocenteredtilde];
+ 0x01a0 = [Ohorn];
+ 0x01a1 = [ohorn];
+ 0x01a2 = [Oi];
+ 0x01a3 = [oi];
+ 0x01a4 = [Phook];
+ 0x01a5 = [phook];
+ 0x01a6 = [yr];
+ 0x01a7 = [Tonetwo];
+ 0x01a8 = [tonetwo];
+ 0x01a9 = [Esh];
+ 0x01aa = [eshreversedloop];
+ 0x01ab = [tpalatalhook];
+ 0x01ac = [Thook];
+ 0x01ad = [thook];
+ 0x01ae = [Tretroflexhook];
+ 0x01af = [Uhorn];
+ 0x01b0 = [uhorn];
+ 0x01b1 = [Upsilonafrican];
+ 0x01b2 = [Vhook];
+ 0x01b3 = [Yhook];
+ 0x01b4 = [yhook];
+ 0x01b5 = [Zstroke];
+ 0x01b6 = [zstroke];
+ 0x01b7 = [Ezh];
+ 0x01b8 = [Ezhreversed];
+ 0x01b9 = [ezhreversed];
+ 0x01ba = [ezhtail];
+ 0x01bb = [twostroke];
+ 0x01bc = [Tonefive];
+ 0x01bd = [tonefive];
+ 0x01be = [glottalinvertedstroke];
+ 0x01bf = [wynn];
+ 0x01c0 = [clickdental];
+ 0x01c1 = [clicklateral];
+ 0x01c2 = [clickalveolar];
+ 0x01c3 = [clickretroflex];
+ 0x01c4 = [DZcaron];
+ 0x01c5 = [Dzcaron];
+ 0x01c6 = [dzcaron];
+ 0x01c7 = [LJ];
+ 0x01c8 = [Lj];
+ 0x01c9 = [lj];
+ 0x01ca = [NJ];
+ 0x01cb = [Nj];
+ 0x01cc = [nj];
+ 0x01cd = [Acaron];
+ 0x01ce = [acaron];
+ 0x01cf = [Icaron];
+ 0x01d0 = [icaron];
+ 0x01d1 = [Ocaron];
+ 0x01d2 = [ocaron];
+ 0x01d3 = [Ucaron];
+ 0x01d4 = [ucaron];
+ 0x01d5 = [Udieresismacron];
+ 0x01d6 = [udieresismacron];
+ 0x01d7 = [Udieresisacute];
+ 0x01d8 = [udieresisacute];
+ 0x01d9 = [Udieresiscaron];
+ 0x01da = [udieresiscaron];
+ 0x01db = [Udieresisgrave];
+ 0x01dc = [udieresisgrave];
+ 0x01dd = [eturned];
+ 0x01de = [Adieresismacron];
+ 0x01df = [adieresismacron];
+ 0x01e0 = [Adotmacron];
+ 0x01e1 = [adotmacron];
+ 0x01e2 = [AEmacron];
+ 0x01e3 = [aemacron];
+ 0x01e4 = [Gstroke];
+ 0x01e5 = [gstroke];
+ 0x01e6 = [Gcaron];
+ 0x01e7 = [gcaron];
+ 0x01e8 = [Kcaron];
+ 0x01e9 = [kcaron];
+ 0x01ea = [Oogonek];
+ 0x01eb = [oogonek];
+ 0x01ec = [Oogonekmacron];
+ 0x01ed = [oogonekmacron];
+ 0x01ee = [Ezhcaron];
+ 0x01ef = [ezhcaron];
+ 0x01f0 = [jcaron];
+ 0x01f1 = [DZ];
+ 0x01f2 = [Dz];
+ 0x01f3 = [dz];
+ 0x01f4 = [Gacute];
+ 0x01f5 = [gacute];
+ 0x01fa = [Aringacute];
+ 0x01fb = [aringacute];
+ 0x01fc = [AEacute];
+ 0x01fd = [aeacute];
+ 0x01fe = [Oslashacute, Ostrokeacute];
+ 0x01ff = [oslashacute, ostrokeacute];
+ 0x0200 = [Adblgrave];
+ 0x0201 = [adblgrave];
+ 0x0202 = [Ainvertedbreve];
+ 0x0203 = [ainvertedbreve];
+ 0x0204 = [Edblgrave];
+ 0x0205 = [edblgrave];
+ 0x0206 = [Einvertedbreve];
+ 0x0207 = [einvertedbreve];
+ 0x0208 = [Idblgrave];
+ 0x0209 = [idblgrave];
+ 0x020a = [Iinvertedbreve];
+ 0x020b = [iinvertedbreve];
+ 0x020c = [Odblgrave];
+ 0x020d = [odblgrave];
+ 0x020e = [Oinvertedbreve];
+ 0x020f = [oinvertedbreve];
+ 0x0210 = [Rdblgrave];
+ 0x0211 = [rdblgrave];
+ 0x0212 = [Rinvertedbreve];
+ 0x0213 = [rinvertedbreve];
+ 0x0214 = [Udblgrave];
+ 0x0215 = [udblgrave];
+ 0x0216 = [Uinvertedbreve];
+ 0x0217 = [uinvertedbreve];
+ 0x0218 = [Scommaaccent];
+ 0x0219 = [scommaaccent];
+ 0x0237 = [dotlessj];
+ 0x0250 = [aturned];
+ 0x0251 = [ascript];
+ 0x0252 = [ascriptturned];
+ 0x0253 = [bhook];
+ 0x0254 = [oopen];
+ 0x0255 = [ccurl];
+ 0x0256 = [dtail];
+ 0x0257 = [dhook];
+ 0x0258 = [ereversed];
+ 0x0259 = [schwa];
+ 0x025a = [schwahook];
+ 0x025b = [eopen];
+ 0x025c = [eopenreversed];
+ 0x025d = [eopenreversedhook];
+ 0x025e = [eopenreversedclosed];
+ 0x025f = [jdotlessstroke];
+ 0x0260 = [ghook];
+ 0x0261 = [gscript];
+ 0x0263 = [gammalatinsmall];
+ 0x0264 = [ramshorn];
+ 0x0265 = [hturned];
+ 0x0266 = [hhook];
+ 0x0267 = [henghook];
+ 0x0268 = [istroke];
+ 0x0269 = [iotalatin];
+ 0x026b = [lmiddletilde];
+ 0x026c = [lbelt];
+ 0x026d = [lhookretroflex];
+ 0x026e = [lezh];
+ 0x026f = [mturned];
+ 0x0270 = [mlonglegturned];
+ 0x0271 = [mhook];
+ 0x0272 = [nhookleft];
+ 0x0273 = [nhookretroflex];
+ 0x0275 = [obarred];
+ 0x0277 = [omegalatinclosed];
+ 0x0278 = [philatin];
+ 0x0279 = [rturned];
+ 0x027a = [rlonglegturned];
+ 0x027b = [rhookturned];
+ 0x027c = [rlongleg];
+ 0x027d = [rhook];
+ 0x027e = [rfishhook];
+ 0x027f = [rfishhookreversed];
+ 0x0281 = [Rsmallinverted];
+ 0x0282 = [shook];
+ 0x0283 = [esh];
+ 0x0284 = [dotlessjstrokehook];
+ 0x0285 = [eshsquatreversed];
+ 0x0286 = [eshcurl];
+ 0x0287 = [tturned];
+ 0x0288 = [tretroflexhook];
+ 0x0289 = [ubar];
+ 0x028a = [upsilonlatin];
+ 0x028b = [vhook];
+ 0x028c = [vturned];
+ 0x028d = [wturned];
+ 0x028e = [yturned];
+ 0x0290 = [zretroflexhook];
+ 0x0291 = [zcurl];
+ 0x0292 = [ezh];
+ 0x0293 = [ezhcurl];
+ 0x0294 = [glottalstop];
+ 0x0295 = [glottalstopreversed];
+ 0x0296 = [glottalstopinverted];
+ 0x0297 = [cstretched];
+ 0x0298 = [bilabialclick];
+ 0x029a = [eopenclosed];
+ 0x029b = [Gsmallhook];
+ 0x029d = [jcrossedtail];
+ 0x029e = [kturned];
+ 0x02a0 = [qhook];
+ 0x02a1 = [glottalstopstroke];
+ 0x02a2 = [glottalstopstrokereversed];
+ 0x02a3 = [dzaltone];
+ 0x02a4 = [dezh];
+ 0x02a5 = [dzcurl];
+ 0x02a6 = [ts];
+ 0x02a7 = [tesh];
+ 0x02a8 = [tccurl];
+ 0x02b0 = [hsuperior];
+ 0x02b1 = [hhooksuperior];
+ 0x02b2 = [jsuperior];
+ 0x02b4 = [rturnedsuperior];
+ 0x02b5 = [rhookturnedsuperior];
+ 0x02b6 = [Rsmallinvertedsuperior];
+ 0x02b7 = [wsuperior];
+ 0x02b8 = [ysuperior];
+ 0x02b9 = [primemod];
+ 0x02ba = [dblprimemod];
+ 0x02bb = [commaturnedmod];
+ 0x02bc = [afii57929, apostrophemod];
+ 0x02bd = [afii64937, commareversedmod];
+ 0x02be = [ringhalfright];
+ 0x02bf = [ringhalfleft];
+ 0x02c0 = [glottalstopmod];
+ 0x02c1 = [glottalstopreversedmod];
+ 0x02c2 = [arrowheadleftmod];
+ 0x02c3 = [arrowheadrightmod];
+ 0x02c4 = [arrowheadupmod];
+ 0x02c5 = [arrowheaddownmod];
+ 0x02c6 = [circumflex];
+ 0x02c7 = [caron];
+ 0x02c8 = [verticallinemod];
+ 0x02c9 = [firsttonechinese];
+ 0x02ca = [secondtonechinese];
+ 0x02cb = [fourthtonechinese];
+ 0x02cc = [verticallinelowmod];
+ 0x02cd = [macronlowmod];
+ 0x02ce = [gravelowmod];
+ 0x02cf = [acutelowmod];
+ 0x02d0 = [colontriangularmod];
+ 0x02d1 = [colontriangularhalfmod];
+ 0x02d2 = [ringhalfrightcentered];
+ 0x02d3 = [ringhalfleftcentered];
+ 0x02d4 = [uptackmod];
+ 0x02d5 = [downtackmod];
+ 0x02d6 = [plusmod];
+ 0x02d7 = [minusmod];
+ 0x02d8 = [breve];
+ 0x02d9 = [dotaccent];
+ 0x02da = [ring];
+ 0x02db = [ogonek];
+ 0x02dc = [ilde, tilde];
+ 0x02dd = [hungarumlaut];
+ 0x02de = [rhotichookmod];
+ 0x02e0 = [gammasuperior];
+ 0x02e3 = [xsuperior];
+ 0x02e4 = [glottalstopreversedsuperior];
+ 0x02e5 = [tonebarextrahighmod];
+ 0x02e6 = [tonebarhighmod];
+ 0x02e7 = [tonebarmidmod];
+ 0x02e8 = [tonebarlowmod];
+ 0x02e9 = [tonebarextralowmod];
+ 0x0300 = [gravecmb, gravecomb];
+ 0x0301 = [acutecmb, acutecomb];
+ 0x0302 = [circumflexcmb, hatwide, hatwider, hatwiderr];
+ 0x0303 = [tildecmb, tildecomb, tildewide, tildewider, tildewiderr];
+ 0x0304 = [macroncmb];
+ 0x0305 = [overlinecmb];
+ 0x0306 = [brevecmb];
+ 0x0307 = [dotaccentcmb];
+ 0x0308 = [dieresiscmb];
+ 0x0309 = [hookabovecomb, hookcmb];
+ 0x030a = [ringcmb];
+ 0x030b = [hungarumlautcmb];
+ 0x030c = [caroncmb];
+ 0x030d = [verticallineabovecmb];
+ 0x030e = [dblverticallineabovecmb];
+ 0x030f = [dblgravecmb];
+ 0x0310 = [candrabinducmb];
+ 0x0311 = [breveinvertedcmb];
+ 0x0312 = [commaturnedabovecmb];
+ 0x0313 = [commaabovecmb];
+ 0x0314 = [commareversedabovecmb];
+ 0x0315 = [commaaboverightcmb];
+ 0x0316 = [gravebelowcmb];
+ 0x0317 = [acutebelowcmb];
+ 0x0318 = [lefttackbelowcmb];
+ 0x0319 = [righttackbelowcmb];
+ 0x031a = [leftangleabovecmb];
+ 0x031b = [horncmb];
+ 0x031c = [ringhalfleftbelowcmb];
+ 0x031d = [uptackbelowcmb];
+ 0x031e = [downtackbelowcmb];
+ 0x031f = [plusbelowcmb];
+ 0x0320 = [minusbelowcmb];
+ 0x0321 = [hookpalatalizedbelowcmb];
+ 0x0322 = [hookretroflexbelowcmb];
+ 0x0323 = [dotbelowcmb, dotbelowcomb];
+ 0x0324 = [dieresisbelowcmb];
+ 0x0325 = [ringbelowcmb];
+ 0x0327 = [cedillacmb];
+ 0x0328 = [ogonekcmb];
+ 0x0329 = [verticallinebelowcmb];
+ 0x032a = [bridgebelowcmb];
+ 0x032b = [dblarchinvertedbelowcmb];
+ 0x032c = [caronbelowcmb];
+ 0x032d = [circumflexbelowcmb];
+ 0x032e = [brevebelowcmb];
+ 0x032f = [breveinvertedbelowcmb];
+ 0x0330 = [tildebelowcmb];
+ 0x0331 = [macronbelowcmb];
+ 0x0332 = [lowlinecmb];
+ 0x0333 = [dbllowlinecmb];
+ 0x0334 = [tildeoverlaycmb];
+ 0x0335 = [strokeshortoverlaycmb];
+ 0x0336 = [strokelongoverlaycmb];
+ 0x0337 = [solidusshortoverlaycmb];
+ 0x0338 = [negationslash, soliduslongoverlaycmb];
+ 0x0339 = [ringhalfrightbelowcmb];
+ 0x033a = [bridgeinvertedbelowcmb];
+ 0x033b = [squarebelowcmb];
+ 0x033c = [seagullbelowcmb];
+ 0x033d = [xabovecmb];
+ 0x033e = [tildeverticalcmb];
+ 0x033f = [dbloverlinecmb];
+ 0x0340 = [gravetonecmb];
+ 0x0341 = [acutetonecmb];
+ 0x0342 = [perispomenigreekcmb];
+ 0x0343 = [koroniscmb];
+ 0x0344 = [dialytikatonoscmb];
+ 0x0345 = [ypogegrammenigreekcmb];
+ 0x0360 = [tildedoublecmb];
+ 0x0361 = [breveinverteddoublecmb];
+ 0x0374 = [numeralsigngreek];
+ 0x0375 = [numeralsignlowergreek];
+ 0x037a = [ypogegrammeni];
+ 0x037e = [questiongreek];
+ 0x0384 = [tonos];
+ 0x0385 = [dialytikatonos, dieresistonos];
+ 0x0386 = [Alphatonos];
+ 0x0387 = [anoteleia];
+ 0x0388 = [Epsilontonos];
+ 0x0389 = [Etatonos];
+ 0x038a = [Iotatonos];
+ 0x038c = [Omicrontonos];
+ 0x038e = [Upsilontonos];
+ 0x038f = [Omegatonos];
+ 0x0390 = [iotadieresistonos];
+ 0x0391 = [Alpha];
+ 0x0392 = [Beta];
+ 0x0393 = [Gamma];
+ 0x0394 = [Deltagreek];
+ 0x0395 = [Epsilon];
+ 0x0396 = [Zeta];
+ 0x0397 = [Eta];
+ 0x0398 = [Theta];
+ 0x0399 = [Iota];
+ 0x039a = [Kappa];
+ 0x039b = [Lambda];
+ 0x039c = [Mu];
+ 0x039d = [Nu];
+ 0x039e = [Xi];
+ 0x039f = [Omicron];
+ 0x03a0 = [Pi];
+ 0x03a1 = [Rho];
+ 0x03a3 = [Sigma];
+ 0x03a4 = [Tau];
+ 0x03a5 = [Upsilon];
+ 0x03a6 = [Phi];
+ 0x03a7 = [Chi];
+ 0x03a8 = [Psi];
+ 0x03a9 = [Omegagreek];
+ 0x03aa = [Iotadieresis];
+ 0x03ab = [Upsilondieresis];
+ 0x03ac = [alphatonos];
+ 0x03ad = [epsilontonos];
+ 0x03ae = [etatonos];
+ 0x03af = [iotatonos];
+ 0x03b0 = [upsilondieresistonos];
+ 0x03b1 = [alpha];
+ 0x03b2 = [beta];
+ 0x03b3 = [gamma];
+ 0x03b4 = [delta];
+ 0x03b5 = [epsilon];
+ 0x03b6 = [zeta];
+ 0x03b7 = [eta];
+ 0x03b8 = [theta];
+ 0x03b9 = [iota];
+ 0x03ba = [kappa];
+ 0x03bb = [lambda];
+ 0x03bc = [mugreek];
+ 0x03bd = [nu];
+ 0x03be = [xi];
+ 0x03bf = [omicron];
+ 0x03c0 = [pi];
+ 0x03c1 = [rho];
+ 0x03c2 = [sigma1, sigmafinal];
+ 0x03c3 = [sigma];
+ 0x03c4 = [tau];
+ 0x03c5 = [upsilon];
+ 0x03c6 = [phi];
+ 0x03c7 = [chi];
+ 0x03c8 = [psi];
+ 0x03c9 = [omega];
+ 0x03ca = [iotadieresis];
+ 0x03cb = [upsilondieresis];
+ 0x03cc = [omicrontonos];
+ 0x03cd = [upsilontonos];
+ 0x03ce = [omegatonos];
+ 0x03d0 = [betasymbolgreek];
+ 0x03d1 = [theta1, thetasymbolgreek];
+ 0x03d2 = [Upsilon1, Upsilonhooksymbol];
+ 0x03d3 = [Upsilonacutehooksymbolgreek];
+ 0x03d4 = [Upsilondieresishooksymbolgreek];
+ 0x03d5 = [phi2, phisymbolgreek];
+ 0x03d6 = [omega1, pi1, pisymbolgreek];
+ 0x03da = [Stigmagreek];
+ 0x03dc = [Digammagreek];
+ 0x03de = [Koppagreek];
+ 0x03e0 = [Sampigreek];
+ 0x03e2 = [Sheicoptic];
+ 0x03e3 = [sheicoptic];
+ 0x03e4 = [Feicoptic];
+ 0x03e5 = [feicoptic];
+ 0x03e6 = [Kheicoptic];
+ 0x03e7 = [kheicoptic];
+ 0x03e8 = [Horicoptic];
+ 0x03e9 = [horicoptic];
+ 0x03ea = [Gangiacoptic];
+ 0x03eb = [gangiacoptic];
+ 0x03ec = [Shimacoptic];
+ 0x03ed = [shimacoptic];
+ 0x03ee = [Deicoptic];
+ 0x03ef = [deicoptic];
+ 0x03f0 = [kappasymbolgreek];
+ 0x03f1 = [rho1, rhosymbolgreek];
+ 0x03f2 = [sigmalunatesymbolgreek];
+ 0x03f3 = [yotgreek];
+ 0x03f5 = [epsilon1];
+ 0x0401 = [afii10023, Iocyrillic];
+ 0x0402 = [afii10051, Djecyrillic];
+ 0x0403 = [afii10052, Gjecyrillic];
+ 0x0404 = [afii10053, Ecyrillic];
+ 0x0405 = [afii10054, Dzecyrillic];
+ 0x0406 = [afii10055, Icyrillic];
+ 0x0407 = [afii10056, Yicyrillic];
+ 0x0408 = [afii10057, Jecyrillic];
+ 0x0409 = [afii10058, Ljecyrillic];
+ 0x040a = [afii10059, Njecyrillic];
+ 0x040b = [afii10060, Tshecyrillic];
+ 0x040c = [afii10061, Kjecyrillic];
+ 0x040e = [afii10062, Ushortcyrillic];
+ 0x040f = [afii10145, Dzhecyrillic];
+ 0x0410 = [Acyrillic, afii10017];
+ 0x0411 = [afii10018, Becyrillic];
+ 0x0412 = [afii10019, Vecyrillic];
+ 0x0413 = [afii10020, Gecyrillic];
+ 0x0414 = [afii10021, Decyrillic];
+ 0x0415 = [afii10022, Iecyrillic];
+ 0x0416 = [afii10024, Zhecyrillic];
+ 0x0417 = [afii10025, Zecyrillic];
+ 0x0418 = [afii10026, Iicyrillic];
+ 0x0419 = [afii10027, Iishortcyrillic];
+ 0x041a = [afii10028, Kacyrillic];
+ 0x041b = [afii10029, Elcyrillic];
+ 0x041c = [afii10030, Emcyrillic];
+ 0x041d = [afii10031, Encyrillic];
+ 0x041e = [afii10032, Ocyrillic];
+ 0x041f = [afii10033, Pecyrillic];
+ 0x0420 = [afii10034, Ercyrillic];
+ 0x0421 = [afii10035, Escyrillic];
+ 0x0422 = [afii10036, Tecyrillic];
+ 0x0423 = [afii10037, Ucyrillic];
+ 0x0424 = [afii10038, Efcyrillic];
+ 0x0425 = [afii10039, Khacyrillic];
+ 0x0426 = [afii10040, Tsecyrillic];
+ 0x0427 = [afii10041, Checyrillic];
+ 0x0428 = [afii10042, Shacyrillic];
+ 0x0429 = [afii10043, Shchacyrillic];
+ 0x042a = [afii10044, Hardsigncyrillic];
+ 0x042b = [afii10045, Yericyrillic];
+ 0x042c = [afii10046, Softsigncyrillic];
+ 0x042d = [afii10047, Ereversedcyrillic];
+ 0x042e = [afii10048, IUcyrillic];
+ 0x042f = [afii10049, IAcyrillic];
+ 0x0430 = [acyrillic, afii10065];
+ 0x0431 = [afii10066, becyrillic];
+ 0x0432 = [afii10067, vecyrillic];
+ 0x0433 = [afii10068, gecyrillic];
+ 0x0434 = [afii10069, decyrillic];
+ 0x0435 = [afii10070, iecyrillic];
+ 0x0436 = [afii10072, zhecyrillic];
+ 0x0437 = [afii10073, zecyrillic];
+ 0x0438 = [afii10074, iicyrillic];
+ 0x0439 = [afii10075, iishortcyrillic];
+ 0x043a = [afii10076, kacyrillic];
+ 0x043b = [afii10077, elcyrillic];
+ 0x043c = [afii10078, emcyrillic];
+ 0x043d = [afii10079, encyrillic];
+ 0x043e = [afii10080, ocyrillic];
+ 0x043f = [afii10081, pecyrillic];
+ 0x0440 = [afii10082, ercyrillic];
+ 0x0441 = [afii10083, escyrillic];
+ 0x0442 = [afii10084, tecyrillic];
+ 0x0443 = [afii10085, ucyrillic];
+ 0x0444 = [afii10086, efcyrillic];
+ 0x0445 = [afii10087, khacyrillic];
+ 0x0446 = [afii10088, tsecyrillic];
+ 0x0447 = [afii10089, checyrillic];
+ 0x0448 = [afii10090, shacyrillic];
+ 0x0449 = [afii10091, shchacyrillic];
+ 0x044a = [afii10092, hardsigncyrillic];
+ 0x044b = [afii10093, yericyrillic];
+ 0x044c = [afii10094, softsigncyrillic];
+ 0x044d = [afii10095, ereversedcyrillic];
+ 0x044e = [afii10096, iucyrillic];
+ 0x044f = [afii10097, iacyrillic];
+ 0x0451 = [afii10071, iocyrillic];
+ 0x0452 = [afii10099, djecyrillic];
+ 0x0453 = [afii10100, gjecyrillic];
+ 0x0454 = [afii10101, ecyrillic];
+ 0x0455 = [afii10102, dzecyrillic];
+ 0x0456 = [afii10103, icyrillic];
+ 0x0457 = [afii10104, yicyrillic];
+ 0x0458 = [afii10105, jecyrillic];
+ 0x0459 = [afii10106, ljecyrillic];
+ 0x045a = [afii10107, njecyrillic];
+ 0x045b = [afii10108, tshecyrillic];
+ 0x045c = [afii10109, kjecyrillic];
+ 0x045e = [afii10110, ushortcyrillic];
+ 0x045f = [afii10193, dzhecyrillic];
+ 0x0460 = [Omegacyrillic];
+ 0x0461 = [omegacyrillic];
+ 0x0462 = [afii10146, Yatcyrillic];
+ 0x0463 = [afii10194, yatcyrillic];
+ 0x0464 = [Eiotifiedcyrillic];
+ 0x0465 = [eiotifiedcyrillic];
+ 0x0466 = [Yuslittlecyrillic];
+ 0x0467 = [yuslittlecyrillic];
+ 0x0468 = [Yuslittleiotifiedcyrillic];
+ 0x0469 = [yuslittleiotifiedcyrillic];
+ 0x046a = [Yusbigcyrillic];
+ 0x046b = [yusbigcyrillic];
+ 0x046c = [Yusbigiotifiedcyrillic];
+ 0x046d = [yusbigiotifiedcyrillic];
+ 0x046e = [Ksicyrillic];
+ 0x046f = [ksicyrillic];
+ 0x0470 = [Psicyrillic];
+ 0x0471 = [psicyrillic];
+ 0x0472 = [afii10147, Fitacyrillic];
+ 0x0473 = [afii10195, fitacyrillic];
+ 0x0474 = [afii10148, Izhitsacyrillic];
+ 0x0475 = [afii10196, izhitsacyrillic];
+ 0x0476 = [Izhitsadblgravecyrillic];
+ 0x0477 = [izhitsadblgravecyrillic];
+ 0x0478 = [Ukcyrillic];
+ 0x0479 = [ukcyrillic];
+ 0x047a = [Omegaroundcyrillic];
+ 0x047b = [omegaroundcyrillic];
+ 0x047c = [Omegatitlocyrillic];
+ 0x047d = [omegatitlocyrillic];
+ 0x047e = [Otcyrillic];
+ 0x047f = [otcyrillic];
+ 0x0480 = [Koppacyrillic];
+ 0x0481 = [koppacyrillic];
+ 0x0482 = [thousandcyrillic];
+ 0x0483 = [titlocyrilliccmb];
+ 0x0484 = [palatalizationcyrilliccmb];
+ 0x0485 = [dasiapneumatacyrilliccmb];
+ 0x0486 = [psilipneumatacyrilliccmb];
+ 0x0490 = [afii10050, Gheupturncyrillic];
+ 0x0491 = [afii10098, gheupturncyrillic];
+ 0x0492 = [Ghestrokecyrillic];
+ 0x0493 = [ghestrokecyrillic];
+ 0x0494 = [Ghemiddlehookcyrillic];
+ 0x0495 = [ghemiddlehookcyrillic];
+ 0x0496 = [Zhedescendercyrillic];
+ 0x0497 = [zhedescendercyrillic];
+ 0x0498 = [Zedescendercyrillic];
+ 0x0499 = [zedescendercyrillic];
+ 0x049a = [Kadescendercyrillic];
+ 0x049b = [kadescendercyrillic];
+ 0x049c = [Kaverticalstrokecyrillic];
+ 0x049d = [kaverticalstrokecyrillic];
+ 0x049e = [Kastrokecyrillic];
+ 0x049f = [kastrokecyrillic];
+ 0x04a0 = [Kabashkircyrillic];
+ 0x04a1 = [kabashkircyrillic];
+ 0x04a2 = [Endescendercyrillic];
+ 0x04a3 = [endescendercyrillic];
+ 0x04a4 = [Enghecyrillic];
+ 0x04a5 = [enghecyrillic];
+ 0x04a6 = [Pemiddlehookcyrillic];
+ 0x04a7 = [pemiddlehookcyrillic];
+ 0x04a8 = [Haabkhasiancyrillic];
+ 0x04a9 = [haabkhasiancyrillic];
+ 0x04aa = [Esdescendercyrillic];
+ 0x04ab = [esdescendercyrillic];
+ 0x04ac = [Tedescendercyrillic];
+ 0x04ad = [tedescendercyrillic];
+ 0x04ae = [Ustraightcyrillic];
+ 0x04af = [ustraightcyrillic];
+ 0x04b0 = [Ustraightstrokecyrillic];
+ 0x04b1 = [ustraightstrokecyrillic];
+ 0x04b2 = [Hadescendercyrillic];
+ 0x04b3 = [hadescendercyrillic];
+ 0x04b4 = [Tetsecyrillic];
+ 0x04b5 = [tetsecyrillic];
+ 0x04b6 = [Chedescendercyrillic];
+ 0x04b7 = [chedescendercyrillic];
+ 0x04b8 = [Cheverticalstrokecyrillic];
+ 0x04b9 = [cheverticalstrokecyrillic];
+ 0x04ba = [Shhacyrillic];
+ 0x04bb = [shhacyrillic];
+ 0x04bc = [Cheabkhasiancyrillic];
+ 0x04bd = [cheabkhasiancyrillic];
+ 0x04be = [Chedescenderabkhasiancyrillic];
+ 0x04bf = [chedescenderabkhasiancyrillic];
+ 0x04c0 = [palochkacyrillic];
+ 0x04c1 = [Zhebrevecyrillic];
+ 0x04c2 = [zhebrevecyrillic];
+ 0x04c3 = [Kahookcyrillic];
+ 0x04c4 = [kahookcyrillic];
+ 0x04c7 = [Enhookcyrillic];
+ 0x04c8 = [enhookcyrillic];
+ 0x04cb = [Chekhakassiancyrillic];
+ 0x04cc = [chekhakassiancyrillic];
+ 0x04d0 = [Abrevecyrillic];
+ 0x04d1 = [abrevecyrillic];
+ 0x04d2 = [Adieresiscyrillic];
+ 0x04d3 = [adieresiscyrillic];
+ 0x04d4 = [Aiecyrillic];
+ 0x04d5 = [aiecyrillic];
+ 0x04d6 = [Iebrevecyrillic];
+ 0x04d7 = [iebrevecyrillic];
+ 0x04d8 = [Schwacyrillic];
+ 0x04d9 = [afii10846, schwacyrillic];
+ 0x04da = [Schwadieresiscyrillic];
+ 0x04db = [schwadieresiscyrillic];
+ 0x04dc = [Zhedieresiscyrillic];
+ 0x04dd = [zhedieresiscyrillic];
+ 0x04de = [Zedieresiscyrillic];
+ 0x04df = [zedieresiscyrillic];
+ 0x04e0 = [Dzeabkhasiancyrillic];
+ 0x04e1 = [dzeabkhasiancyrillic];
+ 0x04e2 = [Imacroncyrillic];
+ 0x04e3 = [imacroncyrillic];
+ 0x04e4 = [Idieresiscyrillic];
+ 0x04e5 = [idieresiscyrillic];
+ 0x04e6 = [Odieresiscyrillic];
+ 0x04e7 = [odieresiscyrillic];
+ 0x04e8 = [Obarredcyrillic];
+ 0x04e9 = [obarredcyrillic];
+ 0x04ea = [Obarreddieresiscyrillic];
+ 0x04eb = [obarreddieresiscyrillic];
+ 0x04ee = [Umacroncyrillic];
+ 0x04ef = [umacroncyrillic];
+ 0x04f0 = [Udieresiscyrillic];
+ 0x04f1 = [udieresiscyrillic];
+ 0x04f2 = [Uhungarumlautcyrillic];
+ 0x04f3 = [uhungarumlautcyrillic];
+ 0x04f4 = [Chedieresiscyrillic];
+ 0x04f5 = [chedieresiscyrillic];
+ 0x04f8 = [Yerudieresiscyrillic];
+ 0x04f9 = [yerudieresiscyrillic];
+ 0x0531 = [Aybarmenian];
+ 0x0532 = [Benarmenian];
+ 0x0533 = [Gimarmenian];
+ 0x0534 = [Daarmenian];
+ 0x0535 = [Echarmenian];
+ 0x0536 = [Zaarmenian];
+ 0x0537 = [Eharmenian];
+ 0x0538 = [Etarmenian];
+ 0x0539 = [Toarmenian];
+ 0x053a = [Zhearmenian];
+ 0x053b = [Iniarmenian];
+ 0x053c = [Liwnarmenian];
+ 0x053d = [Xeharmenian];
+ 0x053e = [Caarmenian];
+ 0x053f = [Kenarmenian];
+ 0x0540 = [Hoarmenian];
+ 0x0541 = [Jaarmenian];
+ 0x0542 = [Ghadarmenian];
+ 0x0543 = [Cheharmenian];
+ 0x0544 = [Menarmenian];
+ 0x0545 = [Yiarmenian];
+ 0x0546 = [Nowarmenian];
+ 0x0547 = [Shaarmenian];
+ 0x0548 = [Voarmenian];
+ 0x0549 = [Chaarmenian];
+ 0x054a = [Peharmenian];
+ 0x054b = [Jheharmenian];
+ 0x054c = [Raarmenian];
+ 0x054d = [Seharmenian];
+ 0x054e = [Vewarmenian];
+ 0x054f = [Tiwnarmenian];
+ 0x0550 = [Reharmenian];
+ 0x0551 = [Coarmenian];
+ 0x0552 = [Yiwnarmenian];
+ 0x0553 = [Piwrarmenian];
+ 0x0554 = [Keharmenian];
+ 0x0555 = [Oharmenian];
+ 0x0556 = [Feharmenian];
+ 0x0559 = [ringhalfleftarmenian];
+ 0x055a = [apostrophearmenian];
+ 0x055b = [emphasismarkarmenian];
+ 0x055c = [exclamarmenian];
+ 0x055d = [commaarmenian];
+ 0x055e = [questionarmenian];
+ 0x055f = [abbreviationmarkarmenian];
+ 0x0561 = [aybarmenian];
+ 0x0562 = [benarmenian];
+ 0x0563 = [gimarmenian];
+ 0x0564 = [daarmenian];
+ 0x0565 = [echarmenian];
+ 0x0566 = [zaarmenian];
+ 0x0567 = [eharmenian];
+ 0x0568 = [etarmenian];
+ 0x0569 = [toarmenian];
+ 0x056a = [zhearmenian];
+ 0x056b = [iniarmenian];
+ 0x056c = [liwnarmenian];
+ 0x056d = [xeharmenian];
+ 0x056e = [caarmenian];
+ 0x056f = [kenarmenian];
+ 0x0570 = [hoarmenian];
+ 0x0571 = [jaarmenian];
+ 0x0572 = [ghadarmenian];
+ 0x0573 = [cheharmenian];
+ 0x0574 = [menarmenian];
+ 0x0575 = [yiarmenian];
+ 0x0576 = [nowarmenian];
+ 0x0577 = [shaarmenian];
+ 0x0578 = [voarmenian];
+ 0x0579 = [chaarmenian];
+ 0x057a = [peharmenian];
+ 0x057b = [jheharmenian];
+ 0x057c = [raarmenian];
+ 0x057d = [seharmenian];
+ 0x057e = [vewarmenian];
+ 0x057f = [tiwnarmenian];
+ 0x0580 = [reharmenian];
+ 0x0581 = [coarmenian];
+ 0x0582 = [yiwnarmenian];
+ 0x0583 = [piwrarmenian];
+ 0x0584 = [keharmenian];
+ 0x0585 = [oharmenian];
+ 0x0586 = [feharmenian];
+ 0x0587 = [echyiwnarmenian];
+ 0x0589 = [periodarmenian];
+ 0x0591 = [etnahtafoukhhebrew, etnahtafoukhlefthebrew, etnahtahebrew, etnahtalefthebrew];
+ 0x0592 = [segoltahebrew];
+ 0x0593 = [shalshelethebrew];
+ 0x0594 = [zaqefqatanhebrew];
+ 0x0595 = [zaqefgadolhebrew];
+ 0x0596 = [tipehahebrew, tipehalefthebrew];
+ 0x0597 = [reviahebrew, reviamugrashhebrew];
+ 0x0598 = [zarqahebrew];
+ 0x0599 = [pashtahebrew];
+ 0x059a = [yetivhebrew];
+ 0x059b = [tevirhebrew, tevirlefthebrew];
+ 0x059c = [gereshaccenthebrew];
+ 0x059d = [gereshmuqdamhebrew];
+ 0x059e = [gershayimaccenthebrew];
+ 0x059f = [qarneyparahebrew];
+ 0x05a0 = [telishagedolahebrew];
+ 0x05a1 = [pazerhebrew];
+ 0x05a3 = [munahhebrew, munahlefthebrew];
+ 0x05a4 = [mahapakhhebrew, mahapakhlefthebrew];
+ 0x05a5 = [merkhahebrew, merkhalefthebrew];
+ 0x05a6 = [merkhakefulahebrew, merkhakefulalefthebrew];
+ 0x05a7 = [dargahebrew, dargalefthebrew];
+ 0x05a8 = [qadmahebrew];
+ 0x05a9 = [telishaqetanahebrew];
+ 0x05aa = [yerahbenyomohebrew, yerahbenyomolefthebrew];
+ 0x05ab = [olehebrew];
+ 0x05ac = [iluyhebrew];
+ 0x05ad = [dehihebrew];
+ 0x05ae = [zinorhebrew];
+ 0x05af = [masoracirclehebrew];
+ 0x05b0 = [afii57799, sheva, sheva115, sheva15, sheva22, sheva2e, shevahebrew, shevanarrowhebrew, shevaquarterhebrew, shevawidehebrew];
+ 0x05b1 = [afii57801, hatafsegol, hatafsegol17, hatafsegol24, hatafsegol30, hatafsegolhebrew, hatafsegolnarrowhebrew, hatafsegolquarterhebrew, hatafsegolwidehebrew];
+ 0x05b2 = [afii57800, hatafpatah, hatafpatah16, hatafpatah23, hatafpatah2f, hatafpatahhebrew, hatafpatahnarrowhebrew, hatafpatahquarterhebrew, hatafpatahwidehebrew];
+ 0x05b3 = [afii57802, hatafqamats, hatafqamats1b, hatafqamats28, hatafqamats34, hatafqamatshebrew, hatafqamatsnarrowhebrew, hatafqamatsquarterhebrew, hatafqamatswidehebrew];
+ 0x05b4 = [afii57793, hiriq, hiriq14, hiriq21, hiriq2d, hiriqhebrew, hiriqnarrowhebrew, hiriqquarterhebrew, hiriqwidehebrew];
+ 0x05b5 = [afii57794, tsere, tsere12, tsere1e, tsere2b, tserehebrew, tserenarrowhebrew, tserequarterhebrew, tserewidehebrew];
+ 0x05b6 = [afii57795, segol, segol13, segol1f, segol2c, segolhebrew, segolnarrowhebrew, segolquarterhebrew, segolwidehebrew];
+ 0x05b7 = [afii57798, patah, patah11, patah1d, patah2a, patahhebrew, patahnarrowhebrew, patahquarterhebrew, patahwidehebrew];
+ 0x05b8 = [afii57797, qamats, qamats10, qamats1a, qamats1c, qamats27, qamats29, qamats33, qamatsde, qamatshebrew, qamatsnarrowhebrew, qamatsqatanhebrew, qamatsqatannarrowhebrew, qamatsqatanquarterhebrew, qamatsqatanwidehebrew, qamatsquarterhebrew, qamatswidehebrew];
+ 0x05b9 = [afii57806, holam, holam19, holam26, holam32, holamhebrew, holamnarrowhebrew, holamquarterhebrew, holamwidehebrew];
+ 0x05bb = [afii57796, qubuts, qubuts18, qubuts25, qubuts31, qubutshebrew, qubutsnarrowhebrew, qubutsquarterhebrew, qubutswidehebrew];
+ 0x05bc = [afii57807, dagesh, dageshhebrew];
+ 0x05bd = [afii57839, siluqhebrew, siluqlefthebrew];
+ 0x05be = [afii57645, maqafhebrew];
+ 0x05bf = [afii57841, rafe, rafehebrew];
+ 0x05c0 = [afii57842, paseqhebrew];
+ 0x05c1 = [afii57804, shindothebrew];
+ 0x05c2 = [afii57803, sindothebrew];
+ 0x05c3 = [afii57658, sofpasuqhebrew];
+ 0x05c4 = [upperdothebrew];
+ 0x05d0 = [afii57664, alef, alefhebrew];
+ 0x05d1 = [afii57665, bet, bethebrew];
+ 0x05d2 = [afii57666, gimel, gimelhebrew];
+ 0x05d3 = [afii57667, dalet, dalethatafpatah, dalethatafpatahhebrew, dalethatafsegol, dalethatafsegolhebrew, dalethebrew, dalethiriq, dalethiriqhebrew, daletholam, daletholamhebrew, daletpatah, daletpatahhebrew, daletqamats, daletqamatshebrew, daletqubuts, daletqubutshebrew, daletsegol, daletsegolhebrew, daletsheva, daletshevahebrew, dalettsere, dalettserehebrew];
+ 0x05d4 = [afii57668, he, hehebrew];
+ 0x05d5 = [afii57669, vav, vavhebrew];
+ 0x05d6 = [afii57670, zayin, zayinhebrew];
+ 0x05d7 = [afii57671, het, hethebrew];
+ 0x05d8 = [afii57672, tet, tethebrew];
+ 0x05d9 = [afii57673, yod, yodhebrew];
+ 0x05da = [afii57674, finalkaf, finalkafhebrew, finalkafqamats, finalkafqamatshebrew, finalkafsheva, finalkafshevahebrew];
+ 0x05db = [afii57675, kaf, kafhebrew];
+ 0x05dc = [afii57676, lamed, lamedhebrew, lamedholam, lamedholamdagesh, lamedholamdageshhebrew, lamedholamhebrew];
+ 0x05dd = [afii57677, finalmem, finalmemhebrew];
+ 0x05de = [afii57678, mem, memhebrew];
+ 0x05df = [afii57679, finalnun, finalnunhebrew];
+ 0x05e0 = [afii57680, nun, nunhebrew];
+ 0x05e1 = [afii57681, samekh, samekhhebrew];
+ 0x05e2 = [afii57682, ayin, ayinhebrew];
+ 0x05e3 = [afii57683, finalpe, finalpehebrew];
+ 0x05e4 = [afii57684, pe, pehebrew];
+ 0x05e5 = [afii57685, finaltsadi, finaltsadihebrew];
+ 0x05e6 = [afii57686, tsadi, tsadihebrew];
+ 0x05e7 = [afii57687, qof, qofhatafpatah, qofhatafpatahhebrew, qofhatafsegol, qofhatafsegolhebrew, qofhebrew, qofhiriq, qofhiriqhebrew, qofholam, qofholamhebrew, qofpatah, qofpatahhebrew, qofqamats, qofqamatshebrew, qofqubuts, qofqubutshebrew, qofsegol, qofsegolhebrew, qofsheva, qofshevahebrew, qoftsere, qoftserehebrew];
+ 0x05e8 = [afii57688, resh, reshhatafpatah, reshhatafpatahhebrew, reshhatafsegol, reshhatafsegolhebrew, reshhebrew, reshhiriq, reshhiriqhebrew, reshholam, reshholamhebrew, reshpatah, reshpatahhebrew, reshqamats, reshqamatshebrew, reshqubuts, reshqubutshebrew, reshsegol, reshsegolhebrew, reshsheva, reshshevahebrew, reshtsere, reshtserehebrew];
+ 0x05e9 = [afii57689, shin, shinhebrew];
+ 0x05ea = [afii57690, tav, tavhebrew];
+ 0x05f0 = [afii57716, vavvavhebrew];
+ 0x05f1 = [afii57717, vavyodhebrew];
+ 0x05f2 = [afii57718, yodyodhebrew];
+ 0x05f3 = [gereshhebrew];
+ 0x05f4 = [gershayimhebrew];
+ 0x060c = [afii57388, commaarabic];
+ 0x061b = [afii57403, semicolonarabic];
+ 0x061f = [afii57407, questionarabic];
+ 0x0621 = [afii57409, hamzaarabic, hamzadammaarabic, hamzadammatanarabic, hamzafathaarabic, hamzafathatanarabic, hamzalowarabic, hamzalowkasraarabic, hamzalowkasratanarabic, hamzasukunarabic];
+ 0x0622 = [afii57410, alefmaddaabovearabic];
+ 0x0623 = [afii57411, alefhamzaabovearabic];
+ 0x0624 = [afii57412, wawhamzaabovearabic];
+ 0x0625 = [afii57413, alefhamzabelowarabic];
+ 0x0626 = [afii57414, yehhamzaabovearabic];
+ 0x0627 = [afii57415, alefarabic];
+ 0x0628 = [afii57416, beharabic];
+ 0x0629 = [afii57417, tehmarbutaarabic];
+ 0x062a = [afii57418, teharabic];
+ 0x062b = [afii57419, theharabic];
+ 0x062c = [afii57420, jeemarabic];
+ 0x062d = [afii57421, haharabic];
+ 0x062e = [afii57422, khaharabic];
+ 0x062f = [afii57423, dalarabic];
+ 0x0630 = [afii57424, thalarabic];
+ 0x0631 = [afii57425, reharabic, rehyehaleflamarabic];
+ 0x0632 = [afii57426, zainarabic];
+ 0x0633 = [afii57427, seenarabic];
+ 0x0634 = [afii57428, sheenarabic];
+ 0x0635 = [afii57429, sadarabic];
+ 0x0636 = [afii57430, dadarabic];
+ 0x0637 = [afii57431, taharabic];
+ 0x0638 = [afii57432, zaharabic];
+ 0x0639 = [afii57433, ainarabic];
+ 0x063a = [afii57434, ghainarabic];
+ 0x0640 = [afii57440, kashidaautoarabic, kashidaautonosidebearingarabic, tatweelarabic];
+ 0x0641 = [afii57441, feharabic];
+ 0x0642 = [afii57442, qafarabic];
+ 0x0643 = [afii57443, kafarabic];
+ 0x0644 = [afii57444, lamarabic];
+ 0x0645 = [afii57445, meemarabic];
+ 0x0646 = [afii57446, noonarabic];
+ 0x0647 = [afii57470, heharabic];
+ 0x0648 = [afii57448, wawarabic];
+ 0x0649 = [afii57449, alefmaksuraarabic];
+ 0x064a = [afii57450, yeharabic];
+ 0x064b = [afii57451, fathatanarabic];
+ 0x064c = [afii57452, dammatanaltonearabic, dammatanarabic];
+ 0x064d = [afii57453, kasratanarabic];
+ 0x064e = [afii57454, fathaarabic, fathalowarabic];
+ 0x064f = [afii57455, dammaarabic, dammalowarabic];
+ 0x0650 = [afii57456, kasraarabic];
+ 0x0651 = [afii57457, shaddaarabic, shaddafathatanarabic];
+ 0x0652 = [afii57458, sukunarabic];
+ 0x0660 = [afii57392, zeroarabic, zerohackarabic];
+ 0x0661 = [afii57393, onearabic, onehackarabic];
+ 0x0662 = [afii57394, twoarabic, twohackarabic];
+ 0x0663 = [afii57395, threearabic, threehackarabic];
+ 0x0664 = [afii57396, fourarabic, fourhackarabic];
+ 0x0665 = [afii57397, fivearabic, fivehackarabic];
+ 0x0666 = [afii57398, sixarabic, sixhackarabic];
+ 0x0667 = [afii57399, sevenarabic, sevenhackarabic];
+ 0x0668 = [afii57400, eightarabic, eighthackarabic];
+ 0x0669 = [afii57401, ninearabic, ninehackarabic];
+ 0x066a = [afii57381, percentarabic];
+ 0x066b = [decimalseparatorarabic, decimalseparatorpersian];
+ 0x066c = [thousandsseparatorarabic, thousandsseparatorpersian];
+ 0x066d = [afii63167, asteriskaltonearabic, asteriskarabic];
+ 0x0679 = [afii57511, tteharabic];
+ 0x067e = [afii57506, peharabic];
+ 0x0686 = [afii57507, tcheharabic];
+ 0x0688 = [afii57512, ddalarabic];
+ 0x0691 = [afii57513, rreharabic];
+ 0x0698 = [afii57508, jeharabic];
+ 0x06a4 = [afii57505, veharabic];
+ 0x06af = [afii57509, gafarabic];
+ 0x06ba = [afii57514, noonghunnaarabic];
+ 0x06c1 = [haaltonearabic, hehaltonearabic];
+ 0x06d1 = [yehthreedotsbelowarabic];
+ 0x06d2 = [afii57519, yehbarreearabic];
+ 0x06d5 = [afii57534];
+ 0x06f0 = [zeropersian];
+ 0x06f1 = [onepersian];
+ 0x06f2 = [twopersian];
+ 0x06f3 = [threepersian];
+ 0x06f4 = [fourpersian];
+ 0x06f5 = [fivepersian];
+ 0x06f6 = [sixpersian];
+ 0x06f7 = [sevenpersian];
+ 0x06f8 = [eightpersian];
+ 0x06f9 = [ninepersian];
+ 0x0901 = [candrabindudeva];
+ 0x0902 = [anusvaradeva];
+ 0x0903 = [visargadeva];
+ 0x0905 = [adeva];
+ 0x0906 = [aadeva];
+ 0x0907 = [ideva];
+ 0x0908 = [iideva];
+ 0x0909 = [udeva];
+ 0x090a = [uudeva];
+ 0x090b = [rvocalicdeva];
+ 0x090c = [lvocalicdeva];
+ 0x090d = [ecandradeva];
+ 0x090e = [eshortdeva];
+ 0x090f = [edeva];
+ 0x0910 = [aideva];
+ 0x0911 = [ocandradeva];
+ 0x0912 = [oshortdeva];
+ 0x0913 = [odeva];
+ 0x0914 = [audeva];
+ 0x0915 = [kadeva];
+ 0x0916 = [khadeva];
+ 0x0917 = [gadeva];
+ 0x0918 = [ghadeva];
+ 0x0919 = [ngadeva];
+ 0x091a = [cadeva];
+ 0x091b = [chadeva];
+ 0x091c = [jadeva];
+ 0x091d = [jhadeva];
+ 0x091e = [nyadeva];
+ 0x091f = [ttadeva];
+ 0x0920 = [tthadeva];
+ 0x0921 = [ddadeva];
+ 0x0922 = [ddhadeva];
+ 0x0923 = [nnadeva];
+ 0x0924 = [tadeva];
+ 0x0925 = [thadeva];
+ 0x0926 = [dadeva];
+ 0x0927 = [dhadeva];
+ 0x0928 = [nadeva];
+ 0x0929 = [nnnadeva];
+ 0x092a = [padeva];
+ 0x092b = [phadeva];
+ 0x092c = [badeva];
+ 0x092d = [bhadeva];
+ 0x092e = [madeva];
+ 0x092f = [yadeva];
+ 0x0930 = [radeva];
+ 0x0931 = [rradeva];
+ 0x0932 = [ladeva];
+ 0x0933 = [lladeva];
+ 0x0934 = [llladeva];
+ 0x0935 = [vadeva];
+ 0x0936 = [shadeva];
+ 0x0937 = [ssadeva];
+ 0x0938 = [sadeva];
+ 0x0939 = [hadeva];
+ 0x093c = [nuktadeva];
+ 0x093d = [avagrahadeva];
+ 0x093e = [aavowelsigndeva];
+ 0x093f = [ivowelsigndeva];
+ 0x0940 = [iivowelsigndeva];
+ 0x0941 = [uvowelsigndeva];
+ 0x0942 = [uuvowelsigndeva];
+ 0x0943 = [rvocalicvowelsigndeva];
+ 0x0944 = [rrvocalicvowelsigndeva];
+ 0x0945 = [ecandravowelsigndeva];
+ 0x0946 = [eshortvowelsigndeva];
+ 0x0947 = [evowelsigndeva];
+ 0x0948 = [aivowelsigndeva];
+ 0x0949 = [ocandravowelsigndeva];
+ 0x094a = [oshortvowelsigndeva];
+ 0x094b = [ovowelsigndeva];
+ 0x094c = [auvowelsigndeva];
+ 0x094d = [viramadeva];
+ 0x0950 = [omdeva];
+ 0x0951 = [udattadeva];
+ 0x0952 = [anudattadeva];
+ 0x0953 = [gravedeva];
+ 0x0954 = [acutedeva];
+ 0x0958 = [qadeva];
+ 0x0959 = [khhadeva];
+ 0x095a = [ghhadeva];
+ 0x095b = [zadeva];
+ 0x095c = [dddhadeva];
+ 0x095d = [rhadeva];
+ 0x095e = [fadeva];
+ 0x095f = [yyadeva];
+ 0x0960 = [rrvocalicdeva];
+ 0x0961 = [llvocalicdeva];
+ 0x0962 = [lvocalicvowelsigndeva];
+ 0x0963 = [llvocalicvowelsigndeva];
+ 0x0964 = [danda];
+ 0x0965 = [dbldanda];
+ 0x0966 = [zerodeva];
+ 0x0967 = [onedeva];
+ 0x0968 = [twodeva];
+ 0x0969 = [threedeva];
+ 0x096a = [fourdeva];
+ 0x096b = [fivedeva];
+ 0x096c = [sixdeva];
+ 0x096d = [sevendeva];
+ 0x096e = [eightdeva];
+ 0x096f = [ninedeva];
+ 0x0970 = [abbreviationsigndeva];
+ 0x0981 = [candrabindubengali];
+ 0x0982 = [anusvarabengali];
+ 0x0983 = [visargabengali];
+ 0x0985 = [abengali];
+ 0x0986 = [aabengali];
+ 0x0987 = [ibengali];
+ 0x0988 = [iibengali];
+ 0x0989 = [ubengali];
+ 0x098a = [uubengali];
+ 0x098b = [rvocalicbengali];
+ 0x098c = [lvocalicbengali];
+ 0x098f = [ebengali];
+ 0x0990 = [aibengali];
+ 0x0993 = [obengali];
+ 0x0994 = [aubengali];
+ 0x0995 = [kabengali];
+ 0x0996 = [khabengali];
+ 0x0997 = [gabengali];
+ 0x0998 = [ghabengali];
+ 0x0999 = [ngabengali];
+ 0x099a = [cabengali];
+ 0x099b = [chabengali];
+ 0x099c = [jabengali];
+ 0x099d = [jhabengali];
+ 0x099e = [nyabengali];
+ 0x099f = [ttabengali];
+ 0x09a0 = [tthabengali];
+ 0x09a1 = [ddabengali];
+ 0x09a2 = [ddhabengali];
+ 0x09a3 = [nnabengali];
+ 0x09a4 = [tabengali];
+ 0x09a5 = [thabengali];
+ 0x09a6 = [dabengali];
+ 0x09a7 = [dhabengali];
+ 0x09a8 = [nabengali];
+ 0x09aa = [pabengali];
+ 0x09ab = [phabengali];
+ 0x09ac = [babengali];
+ 0x09ad = [bhabengali];
+ 0x09ae = [mabengali];
+ 0x09af = [yabengali];
+ 0x09b0 = [rabengali];
+ 0x09b2 = [labengali];
+ 0x09b6 = [shabengali];
+ 0x09b7 = [ssabengali];
+ 0x09b8 = [sabengali];
+ 0x09b9 = [habengali];
+ 0x09bc = [nuktabengali];
+ 0x09be = [aavowelsignbengali];
+ 0x09bf = [ivowelsignbengali];
+ 0x09c0 = [iivowelsignbengali];
+ 0x09c1 = [uvowelsignbengali];
+ 0x09c2 = [uuvowelsignbengali];
+ 0x09c3 = [rvocalicvowelsignbengali];
+ 0x09c4 = [rrvocalicvowelsignbengali];
+ 0x09c7 = [evowelsignbengali];
+ 0x09c8 = [aivowelsignbengali];
+ 0x09cb = [ovowelsignbengali];
+ 0x09cc = [auvowelsignbengali];
+ 0x09cd = [viramabengali];
+ 0x09d7 = [aulengthmarkbengali];
+ 0x09dc = [rrabengali];
+ 0x09dd = [rhabengali];
+ 0x09df = [yyabengali];
+ 0x09e0 = [rrvocalicbengali];
+ 0x09e1 = [llvocalicbengali];
+ 0x09e2 = [lvocalicvowelsignbengali];
+ 0x09e3 = [llvocalicvowelsignbengali];
+ 0x09e6 = [zerobengali];
+ 0x09e7 = [onebengali];
+ 0x09e8 = [twobengali];
+ 0x09e9 = [threebengali];
+ 0x09ea = [fourbengali];
+ 0x09eb = [fivebengali];
+ 0x09ec = [sixbengali];
+ 0x09ed = [sevenbengali];
+ 0x09ee = [eightbengali];
+ 0x09ef = [ninebengali];
+ 0x09f0 = [ramiddlediagonalbengali];
+ 0x09f1 = [ralowerdiagonalbengali];
+ 0x09f2 = [rupeemarkbengali];
+ 0x09f3 = [rupeesignbengali];
+ 0x09f4 = [onenumeratorbengali];
+ 0x09f5 = [twonumeratorbengali];
+ 0x09f6 = [threenumeratorbengali];
+ 0x09f7 = [fournumeratorbengali];
+ 0x09f8 = [denominatorminusonenumeratorbengali];
+ 0x09f9 = [sixteencurrencydenominatorbengali];
+ 0x09fa = [issharbengali];
+ 0x0a02 = [bindigurmukhi];
+ 0x0a05 = [agurmukhi];
+ 0x0a06 = [aagurmukhi];
+ 0x0a07 = [igurmukhi];
+ 0x0a08 = [iigurmukhi];
+ 0x0a09 = [ugurmukhi];
+ 0x0a0a = [uugurmukhi];
+ 0x0a0f = [eegurmukhi];
+ 0x0a10 = [aigurmukhi];
+ 0x0a13 = [oogurmukhi];
+ 0x0a14 = [augurmukhi];
+ 0x0a15 = [kagurmukhi];
+ 0x0a16 = [khagurmukhi];
+ 0x0a17 = [gagurmukhi];
+ 0x0a18 = [ghagurmukhi];
+ 0x0a19 = [ngagurmukhi];
+ 0x0a1a = [cagurmukhi];
+ 0x0a1b = [chagurmukhi];
+ 0x0a1c = [jagurmukhi];
+ 0x0a1d = [jhagurmukhi];
+ 0x0a1e = [nyagurmukhi];
+ 0x0a1f = [ttagurmukhi];
+ 0x0a20 = [tthagurmukhi];
+ 0x0a21 = [ddagurmukhi];
+ 0x0a22 = [ddhagurmukhi];
+ 0x0a23 = [nnagurmukhi];
+ 0x0a24 = [tagurmukhi];
+ 0x0a25 = [thagurmukhi];
+ 0x0a26 = [dagurmukhi];
+ 0x0a27 = [dhagurmukhi];
+ 0x0a28 = [nagurmukhi];
+ 0x0a2a = [pagurmukhi];
+ 0x0a2b = [phagurmukhi];
+ 0x0a2c = [bagurmukhi];
+ 0x0a2d = [bhagurmukhi];
+ 0x0a2e = [magurmukhi];
+ 0x0a2f = [yagurmukhi];
+ 0x0a30 = [ragurmukhi];
+ 0x0a32 = [lagurmukhi];
+ 0x0a35 = [vagurmukhi];
+ 0x0a36 = [shagurmukhi];
+ 0x0a38 = [sagurmukhi];
+ 0x0a39 = [hagurmukhi];
+ 0x0a3c = [nuktagurmukhi];
+ 0x0a3e = [aamatragurmukhi];
+ 0x0a3f = [imatragurmukhi];
+ 0x0a40 = [iimatragurmukhi];
+ 0x0a41 = [umatragurmukhi];
+ 0x0a42 = [uumatragurmukhi];
+ 0x0a47 = [eematragurmukhi];
+ 0x0a48 = [aimatragurmukhi];
+ 0x0a4b = [oomatragurmukhi];
+ 0x0a4c = [aumatragurmukhi];
+ 0x0a4d = [halantgurmukhi];
+ 0x0a59 = [khhagurmukhi];
+ 0x0a5a = [ghhagurmukhi];
+ 0x0a5b = [zagurmukhi];
+ 0x0a5c = [rragurmukhi];
+ 0x0a5e = [fagurmukhi];
+ 0x0a66 = [zerogurmukhi];
+ 0x0a67 = [onegurmukhi];
+ 0x0a68 = [twogurmukhi];
+ 0x0a69 = [threegurmukhi];
+ 0x0a6a = [fourgurmukhi];
+ 0x0a6b = [fivegurmukhi];
+ 0x0a6c = [sixgurmukhi];
+ 0x0a6d = [sevengurmukhi];
+ 0x0a6e = [eightgurmukhi];
+ 0x0a6f = [ninegurmukhi];
+ 0x0a70 = [tippigurmukhi];
+ 0x0a71 = [addakgurmukhi];
+ 0x0a72 = [irigurmukhi];
+ 0x0a73 = [uragurmukhi];
+ 0x0a74 = [ekonkargurmukhi];
+ 0x0a81 = [candrabindugujarati];
+ 0x0a82 = [anusvaragujarati];
+ 0x0a83 = [visargagujarati];
+ 0x0a85 = [agujarati];
+ 0x0a86 = [aagujarati];
+ 0x0a87 = [igujarati];
+ 0x0a88 = [iigujarati];
+ 0x0a89 = [ugujarati];
+ 0x0a8a = [uugujarati];
+ 0x0a8b = [rvocalicgujarati];
+ 0x0a8d = [ecandragujarati];
+ 0x0a8f = [egujarati];
+ 0x0a90 = [aigujarati];
+ 0x0a91 = [ocandragujarati];
+ 0x0a93 = [ogujarati];
+ 0x0a94 = [augujarati];
+ 0x0a95 = [kagujarati];
+ 0x0a96 = [khagujarati];
+ 0x0a97 = [gagujarati];
+ 0x0a98 = [ghagujarati];
+ 0x0a99 = [ngagujarati];
+ 0x0a9a = [cagujarati];
+ 0x0a9b = [chagujarati];
+ 0x0a9c = [jagujarati];
+ 0x0a9d = [jhagujarati];
+ 0x0a9e = [nyagujarati];
+ 0x0a9f = [ttagujarati];
+ 0x0aa0 = [tthagujarati];
+ 0x0aa1 = [ddagujarati];
+ 0x0aa2 = [ddhagujarati];
+ 0x0aa3 = [nnagujarati];
+ 0x0aa4 = [tagujarati];
+ 0x0aa5 = [thagujarati];
+ 0x0aa6 = [dagujarati];
+ 0x0aa7 = [dhagujarati];
+ 0x0aa8 = [nagujarati];
+ 0x0aaa = [pagujarati];
+ 0x0aab = [phagujarati];
+ 0x0aac = [bagujarati];
+ 0x0aad = [bhagujarati];
+ 0x0aae = [magujarati];
+ 0x0aaf = [yagujarati];
+ 0x0ab0 = [ragujarati];
+ 0x0ab2 = [lagujarati];
+ 0x0ab3 = [llagujarati];
+ 0x0ab5 = [vagujarati];
+ 0x0ab6 = [shagujarati];
+ 0x0ab7 = [ssagujarati];
+ 0x0ab8 = [sagujarati];
+ 0x0ab9 = [hagujarati];
+ 0x0abc = [nuktagujarati];
+ 0x0abe = [aavowelsigngujarati];
+ 0x0abf = [ivowelsigngujarati];
+ 0x0ac0 = [iivowelsigngujarati];
+ 0x0ac1 = [uvowelsigngujarati];
+ 0x0ac2 = [uuvowelsigngujarati];
+ 0x0ac3 = [rvocalicvowelsigngujarati];
+ 0x0ac4 = [rrvocalicvowelsigngujarati];
+ 0x0ac5 = [ecandravowelsigngujarati];
+ 0x0ac7 = [evowelsigngujarati];
+ 0x0ac8 = [aivowelsigngujarati];
+ 0x0ac9 = [ocandravowelsigngujarati];
+ 0x0acb = [ovowelsigngujarati];
+ 0x0acc = [auvowelsigngujarati];
+ 0x0acd = [viramagujarati];
+ 0x0ad0 = [omgujarati];
+ 0x0ae0 = [rrvocalicgujarati];
+ 0x0ae6 = [zerogujarati];
+ 0x0ae7 = [onegujarati];
+ 0x0ae8 = [twogujarati];
+ 0x0ae9 = [threegujarati];
+ 0x0aea = [fourgujarati];
+ 0x0aeb = [fivegujarati];
+ 0x0aec = [sixgujarati];
+ 0x0aed = [sevengujarati];
+ 0x0aee = [eightgujarati];
+ 0x0aef = [ninegujarati];
+ 0x0e01 = [kokaithai];
+ 0x0e02 = [khokhaithai];
+ 0x0e03 = [khokhuatthai];
+ 0x0e04 = [khokhwaithai];
+ 0x0e05 = [khokhonthai];
+ 0x0e06 = [khorakhangthai];
+ 0x0e07 = [ngonguthai];
+ 0x0e08 = [chochanthai];
+ 0x0e09 = [chochingthai];
+ 0x0e0a = [chochangthai];
+ 0x0e0b = [sosothai];
+ 0x0e0c = [chochoethai];
+ 0x0e0d = [yoyingthai];
+ 0x0e0e = [dochadathai];
+ 0x0e0f = [topatakthai];
+ 0x0e10 = [thothanthai];
+ 0x0e11 = [thonangmonthothai];
+ 0x0e12 = [thophuthaothai];
+ 0x0e13 = [nonenthai];
+ 0x0e14 = [dodekthai];
+ 0x0e15 = [totaothai];
+ 0x0e16 = [thothungthai];
+ 0x0e17 = [thothahanthai];
+ 0x0e18 = [thothongthai];
+ 0x0e19 = [nonuthai];
+ 0x0e1a = [bobaimaithai];
+ 0x0e1b = [poplathai];
+ 0x0e1c = [phophungthai];
+ 0x0e1d = [fofathai];
+ 0x0e1e = [phophanthai];
+ 0x0e1f = [fofanthai];
+ 0x0e20 = [phosamphaothai];
+ 0x0e21 = [momathai];
+ 0x0e22 = [yoyakthai];
+ 0x0e23 = [roruathai];
+ 0x0e24 = [ruthai];
+ 0x0e25 = [lolingthai];
+ 0x0e26 = [luthai];
+ 0x0e27 = [wowaenthai];
+ 0x0e28 = [sosalathai];
+ 0x0e29 = [sorusithai];
+ 0x0e2a = [sosuathai];
+ 0x0e2b = [hohipthai];
+ 0x0e2c = [lochulathai];
+ 0x0e2d = [oangthai];
+ 0x0e2e = [honokhukthai];
+ 0x0e2f = [paiyannoithai];
+ 0x0e30 = [saraathai];
+ 0x0e31 = [maihanakatthai];
+ 0x0e32 = [saraaathai];
+ 0x0e33 = [saraamthai];
+ 0x0e34 = [saraithai];
+ 0x0e35 = [saraiithai];
+ 0x0e36 = [sarauethai];
+ 0x0e37 = [saraueethai];
+ 0x0e38 = [sarauthai];
+ 0x0e39 = [sarauuthai];
+ 0x0e3a = [phinthuthai];
+ 0x0e3f = [bahtthai];
+ 0x0e40 = [saraethai];
+ 0x0e41 = [saraaethai];
+ 0x0e42 = [saraothai];
+ 0x0e43 = [saraaimaimuanthai];
+ 0x0e44 = [saraaimaimalaithai];
+ 0x0e45 = [lakkhangyaothai];
+ 0x0e46 = [maiyamokthai];
+ 0x0e47 = [maitaikhuthai];
+ 0x0e48 = [maiekthai];
+ 0x0e49 = [maithothai];
+ 0x0e4a = [maitrithai];
+ 0x0e4b = [maichattawathai];
+ 0x0e4c = [thanthakhatthai];
+ 0x0e4d = [nikhahitthai];
+ 0x0e4e = [yamakkanthai];
+ 0x0e4f = [fongmanthai];
+ 0x0e50 = [zerothai];
+ 0x0e51 = [onethai];
+ 0x0e52 = [twothai];
+ 0x0e53 = [threethai];
+ 0x0e54 = [fourthai];
+ 0x0e55 = [fivethai];
+ 0x0e56 = [sixthai];
+ 0x0e57 = [seventhai];
+ 0x0e58 = [eightthai];
+ 0x0e59 = [ninethai];
+ 0x0e5a = [angkhankhuthai];
+ 0x0e5b = [khomutthai];
+ 0x1e00 = [Aringbelow];
+ 0x1e01 = [aringbelow];
+ 0x1e02 = [Bdotaccent];
+ 0x1e03 = [bdotaccent];
+ 0x1e04 = [Bdotbelow];
+ 0x1e05 = [bdotbelow];
+ 0x1e06 = [Blinebelow];
+ 0x1e07 = [blinebelow];
+ 0x1e08 = [Ccedillaacute];
+ 0x1e09 = [ccedillaacute];
+ 0x1e0a = [Ddotaccent];
+ 0x1e0b = [ddotaccent];
+ 0x1e0c = [Ddotbelow];
+ 0x1e0d = [ddotbelow];
+ 0x1e0e = [Dlinebelow];
+ 0x1e0f = [dlinebelow];
+ 0x1e10 = [Dcedilla];
+ 0x1e11 = [dcedilla];
+ 0x1e12 = [Dcircumflexbelow];
+ 0x1e13 = [dcircumflexbelow];
+ 0x1e14 = [Emacrongrave];
+ 0x1e15 = [emacrongrave];
+ 0x1e16 = [Emacronacute];
+ 0x1e17 = [emacronacute];
+ 0x1e18 = [Ecircumflexbelow];
+ 0x1e19 = [ecircumflexbelow];
+ 0x1e1a = [Etildebelow];
+ 0x1e1b = [etildebelow];
+ 0x1e1c = [Ecedillabreve];
+ 0x1e1d = [ecedillabreve];
+ 0x1e1e = [Fdotaccent];
+ 0x1e1f = [fdotaccent];
+ 0x1e20 = [Gmacron];
+ 0x1e21 = [gmacron];
+ 0x1e22 = [Hdotaccent];
+ 0x1e23 = [hdotaccent];
+ 0x1e24 = [Hdotbelow];
+ 0x1e25 = [hdotbelow];
+ 0x1e26 = [Hdieresis];
+ 0x1e27 = [hdieresis];
+ 0x1e28 = [Hcedilla];
+ 0x1e29 = [hcedilla];
+ 0x1e2a = [Hbrevebelow];
+ 0x1e2b = [hbrevebelow];
+ 0x1e2c = [Itildebelow];
+ 0x1e2d = [itildebelow];
+ 0x1e2e = [Idieresisacute];
+ 0x1e2f = [idieresisacute];
+ 0x1e30 = [Kacute];
+ 0x1e31 = [kacute];
+ 0x1e32 = [Kdotbelow];
+ 0x1e33 = [kdotbelow];
+ 0x1e34 = [Klinebelow];
+ 0x1e35 = [klinebelow];
+ 0x1e36 = [Ldotbelow];
+ 0x1e37 = [ldotbelow];
+ 0x1e38 = [Ldotbelowmacron];
+ 0x1e39 = [ldotbelowmacron];
+ 0x1e3a = [Llinebelow];
+ 0x1e3b = [llinebelow];
+ 0x1e3c = [Lcircumflexbelow];
+ 0x1e3d = [lcircumflexbelow];
+ 0x1e3e = [Macute];
+ 0x1e3f = [macute];
+ 0x1e40 = [Mdotaccent];
+ 0x1e41 = [mdotaccent];
+ 0x1e42 = [Mdotbelow];
+ 0x1e43 = [mdotbelow];
+ 0x1e44 = [Ndotaccent];
+ 0x1e45 = [ndotaccent];
+ 0x1e46 = [Ndotbelow];
+ 0x1e47 = [ndotbelow];
+ 0x1e48 = [Nlinebelow];
+ 0x1e49 = [nlinebelow];
+ 0x1e4a = [Ncircumflexbelow];
+ 0x1e4b = [ncircumflexbelow];
+ 0x1e4c = [Otildeacute];
+ 0x1e4d = [otildeacute];
+ 0x1e4e = [Otildedieresis];
+ 0x1e4f = [otildedieresis];
+ 0x1e50 = [Omacrongrave];
+ 0x1e51 = [omacrongrave];
+ 0x1e52 = [Omacronacute];
+ 0x1e53 = [omacronacute];
+ 0x1e54 = [Pacute];
+ 0x1e55 = [pacute];
+ 0x1e56 = [Pdotaccent];
+ 0x1e57 = [pdotaccent];
+ 0x1e58 = [Rdotaccent];
+ 0x1e59 = [rdotaccent];
+ 0x1e5a = [Rdotbelow];
+ 0x1e5b = [rdotbelow];
+ 0x1e5c = [Rdotbelowmacron];
+ 0x1e5d = [rdotbelowmacron];
+ 0x1e5e = [Rlinebelow];
+ 0x1e5f = [rlinebelow];
+ 0x1e60 = [Sdotaccent];
+ 0x1e61 = [sdotaccent];
+ 0x1e62 = [Sdotbelow];
+ 0x1e63 = [sdotbelow];
+ 0x1e64 = [Sacutedotaccent];
+ 0x1e65 = [sacutedotaccent];
+ 0x1e66 = [Scarondotaccent];
+ 0x1e67 = [scarondotaccent];
+ 0x1e68 = [Sdotbelowdotaccent];
+ 0x1e69 = [sdotbelowdotaccent];
+ 0x1e6a = [Tdotaccent];
+ 0x1e6b = [tdotaccent];
+ 0x1e6c = [Tdotbelow];
+ 0x1e6d = [tdotbelow];
+ 0x1e6e = [Tlinebelow];
+ 0x1e6f = [tlinebelow];
+ 0x1e70 = [Tcircumflexbelow];
+ 0x1e71 = [tcircumflexbelow];
+ 0x1e72 = [Udieresisbelow];
+ 0x1e73 = [udieresisbelow];
+ 0x1e74 = [Utildebelow];
+ 0x1e75 = [utildebelow];
+ 0x1e76 = [Ucircumflexbelow];
+ 0x1e77 = [ucircumflexbelow];
+ 0x1e78 = [Utildeacute];
+ 0x1e79 = [utildeacute];
+ 0x1e7a = [Umacrondieresis];
+ 0x1e7b = [umacrondieresis];
+ 0x1e7c = [Vtilde];
+ 0x1e7d = [vtilde];
+ 0x1e7e = [Vdotbelow];
+ 0x1e7f = [vdotbelow];
+ 0x1e80 = [Wgrave];
+ 0x1e81 = [wgrave];
+ 0x1e82 = [Wacute];
+ 0x1e83 = [wacute];
+ 0x1e84 = [Wdieresis];
+ 0x1e85 = [wdieresis];
+ 0x1e86 = [Wdotaccent];
+ 0x1e87 = [wdotaccent];
+ 0x1e88 = [Wdotbelow];
+ 0x1e89 = [wdotbelow];
+ 0x1e8a = [Xdotaccent];
+ 0x1e8b = [xdotaccent];
+ 0x1e8c = [Xdieresis];
+ 0x1e8d = [xdieresis];
+ 0x1e8e = [Ydotaccent];
+ 0x1e8f = [ydotaccent];
+ 0x1e90 = [Zcircumflex];
+ 0x1e91 = [zcircumflex];
+ 0x1e92 = [Zdotbelow];
+ 0x1e93 = [zdotbelow];
+ 0x1e94 = [Zlinebelow];
+ 0x1e95 = [zlinebelow];
+ 0x1e96 = [hlinebelow];
+ 0x1e97 = [tdieresis];
+ 0x1e98 = [wring];
+ 0x1e99 = [yring];
+ 0x1e9a = [arighthalfring];
+ 0x1e9b = [slongdotaccent];
+ 0x1e9e = [Germandbls2];
+ 0x1ea0 = [Adotbelow];
+ 0x1ea1 = [adotbelow];
+ 0x1ea2 = [Ahookabove];
+ 0x1ea3 = [ahookabove];
+ 0x1ea4 = [Acircumflexacute];
+ 0x1ea5 = [acircumflexacute];
+ 0x1ea6 = [Acircumflexgrave];
+ 0x1ea7 = [acircumflexgrave];
+ 0x1ea8 = [Acircumflexhookabove];
+ 0x1ea9 = [acircumflexhookabove];
+ 0x1eaa = [Acircumflextilde];
+ 0x1eab = [acircumflextilde];
+ 0x1eac = [Acircumflexdotbelow];
+ 0x1ead = [acircumflexdotbelow];
+ 0x1eae = [Abreveacute];
+ 0x1eaf = [abreveacute];
+ 0x1eb0 = [Abrevegrave];
+ 0x1eb1 = [abrevegrave];
+ 0x1eb2 = [Abrevehookabove];
+ 0x1eb3 = [abrevehookabove];
+ 0x1eb4 = [Abrevetilde];
+ 0x1eb5 = [abrevetilde];
+ 0x1eb6 = [Abrevedotbelow];
+ 0x1eb7 = [abrevedotbelow];
+ 0x1eb8 = [Edotbelow];
+ 0x1eb9 = [edotbelow];
+ 0x1eba = [Ehookabove];
+ 0x1ebb = [ehookabove];
+ 0x1ebc = [Etilde];
+ 0x1ebd = [etilde];
+ 0x1ebe = [Ecircumflexacute];
+ 0x1ebf = [ecircumflexacute];
+ 0x1ec0 = [Ecircumflexgrave];
+ 0x1ec1 = [ecircumflexgrave];
+ 0x1ec2 = [Ecircumflexhookabove];
+ 0x1ec3 = [ecircumflexhookabove];
+ 0x1ec4 = [Ecircumflextilde];
+ 0x1ec5 = [ecircumflextilde];
+ 0x1ec6 = [Ecircumflexdotbelow];
+ 0x1ec7 = [ecircumflexdotbelow];
+ 0x1ec8 = [Ihookabove];
+ 0x1ec9 = [ihookabove];
+ 0x1eca = [Idotbelow];
+ 0x1ecb = [idotbelow];
+ 0x1ecc = [Odotbelow];
+ 0x1ecd = [odotbelow];
+ 0x1ece = [Ohookabove];
+ 0x1ecf = [ohookabove];
+ 0x1ed0 = [Ocircumflexacute];
+ 0x1ed1 = [ocircumflexacute];
+ 0x1ed2 = [Ocircumflexgrave];
+ 0x1ed3 = [ocircumflexgrave];
+ 0x1ed4 = [Ocircumflexhookabove];
+ 0x1ed5 = [ocircumflexhookabove];
+ 0x1ed6 = [Ocircumflextilde];
+ 0x1ed7 = [ocircumflextilde];
+ 0x1ed8 = [Ocircumflexdotbelow];
+ 0x1ed9 = [ocircumflexdotbelow];
+ 0x1eda = [Ohornacute];
+ 0x1edb = [ohornacute];
+ 0x1edc = [Ohorngrave];
+ 0x1edd = [ohorngrave];
+ 0x1ede = [Ohornhookabove];
+ 0x1edf = [ohornhookabove];
+ 0x1ee0 = [Ohorntilde];
+ 0x1ee1 = [ohorntilde];
+ 0x1ee2 = [Ohorndotbelow];
+ 0x1ee3 = [ohorndotbelow];
+ 0x1ee4 = [Udotbelow];
+ 0x1ee5 = [udotbelow];
+ 0x1ee6 = [Uhookabove];
+ 0x1ee7 = [uhookabove];
+ 0x1ee8 = [Uhornacute];
+ 0x1ee9 = [uhornacute];
+ 0x1eea = [Uhorngrave];
+ 0x1eeb = [uhorngrave];
+ 0x1eec = [Uhornhookabove];
+ 0x1eed = [uhornhookabove];
+ 0x1eee = [Uhorntilde];
+ 0x1eef = [uhorntilde];
+ 0x1ef0 = [Uhorndotbelow];
+ 0x1ef1 = [uhorndotbelow];
+ 0x1ef2 = [Ygrave];
+ 0x1ef3 = [ygrave];
+ 0x1ef4 = [Ydotbelow];
+ 0x1ef5 = [ydotbelow];
+ 0x1ef6 = [Yhookabove];
+ 0x1ef7 = [yhookabove];
+ 0x1ef8 = [Ytilde];
+ 0x1ef9 = [ytilde];
+ 0x2002 = [enspace];
+ 0x200b = [zerowidthspace];
+ 0x200c = [afii61664, compwordmark, cwm, zerowidthnonjoiner];
+ 0x200d = [afii301];
+ 0x200e = [afii299];
+ 0x200f = [afii300];
+ 0x2010 = [hyphen_alt, hyphentwo];
+ 0x2012 = [figuredash];
+ 0x2013 = [endash, rangedash];
+ 0x2014 = [emdash, punctdash];
+ 0x2015 = [afii00208, horizontalbar];
+ 0x2016 = [bardblex, bracerightmid, dblverticalbar];
+ 0x2017 = [dbllowline, underscoredbl];
+ 0x2018 = [quoteleft];
+ 0x2019 = [quoteright];
+ 0x201a = [quotesinglbase];
+ 0x201b = [quoteleftreversed, quotereversed];
+ 0x201c = [quotedblleft];
+ 0x201d = [quotedblright];
+ 0x201e = [quotedblbase];
+ 0x2020 = [dagger];
+ 0x2021 = [daggerdbl];
+ 0x2022 = [bullet];
+ 0x2024 = [onedotenleader];
+ 0x2025 = [twodotenleader, twodotleader];
+ 0x2026 = [ellipsis];
+ 0x202c = [afii61573];
+ 0x202d = [afii61574];
+ 0x202e = [afii61575];
+ 0x2030 = [perthousand];
+ 0x2031 = [pertenthousand];
+ 0x2032 = [minute, prime];
+ 0x2033 = [second];
+ 0x2035 = [primereversed];
+ 0x2039 = [guilsinglleft];
+ 0x203a = [guilsinglright];
+ 0x203b = [referencemark];
+ 0x203c = [exclamdbl];
+ 0x203d = [interrobang];
+ 0x203e = [overline];
+ 0x2040 = [tie];
+ 0x2042 = [asterism];
+ 0x2044 = [fraction];
+ 0x2070 = [zerosuperior];
+ 0x2074 = [foursuperior];
+ 0x2075 = [fivesuperior];
+ 0x2076 = [sixsuperior];
+ 0x2077 = [sevensuperior];
+ 0x2078 = [eightsuperior];
+ 0x2079 = [ninesuperior];
+ 0x207a = [plussuperior];
+ 0x207c = [equalsuperior];
+ 0x207d = [parenleftsuperior];
+ 0x207e = [parenrightsuperior];
+ 0x207f = [nsuperior];
+ 0x2080 = [zeroinferior];
+ 0x2081 = [oneinferior];
+ 0x2082 = [twoinferior];
+ 0x2083 = [threeinferior];
+ 0x2084 = [fourinferior];
+ 0x2085 = [fiveinferior];
+ 0x2086 = [sixinferior];
+ 0x2087 = [seveninferior];
+ 0x2088 = [eightinferior];
+ 0x2089 = [nineinferior];
+ 0x208d = [parenleftinferior];
+ 0x208e = [parenrightinferior];
+ 0x20a1 = [colonmonetary, colonsign];
+ 0x20a2 = [cruzeiro];
+ 0x20a3 = [franc];
+ 0x20a4 = [afii08941, lira];
+ 0x20a7 = [peseta];
+ 0x20a9 = [won];
+ 0x20aa = [afii57636, newsheqelsign, sheqel, sheqelhebrew];
+ 0x20ab = [dong];
+ 0x20ac = [euro, Euro];
+ 0x20d7 = [vector];
+ 0x20dd = [circlecopyrt];
+ 0x2103 = [centigrade];
+ 0x2105 = [afii61248, careof];
+ 0x2109 = [fahrenheit];
+ 0x2111 = [Ifractur, Ifraktur];
+ 0x2113 = [afii61289, lscript, lsquare];
+ 0x2116 = [afii61352, numero];
+ 0x2118 = [weierstrass];
+ 0x211c = [Rfractur, Rfraktur];
+ 0x211e = [prescription];
+ 0x2121 = [telephone];
+ 0x2122 = [trademark];
+ 0x2126 = [Ohm, Omega];
+ 0x212b = [angstrom];
+ 0x212e = [estimated];
+ 0x2135 = [aleph];
+ 0x2153 = [onethird];
+ 0x2154 = [twothirds];
+ 0x215b = [oneeighth];
+ 0x215c = [threeeighths];
+ 0x215d = [fiveeighths];
+ 0x215e = [seveneighths];
+ 0x2160 = [Oneroman];
+ 0x2161 = [Tworoman];
+ 0x2162 = [Threeroman];
+ 0x2163 = [Fourroman];
+ 0x2164 = [Fiveroman];
+ 0x2165 = [Sixroman];
+ 0x2166 = [Sevenroman];
+ 0x2167 = [Eightroman];
+ 0x2168 = [Nineroman];
+ 0x2169 = [Tenroman];
+ 0x216a = [Elevenroman];
+ 0x216b = [Twelveroman];
+ 0x2170 = [oneroman];
+ 0x2171 = [tworoman];
+ 0x2172 = [threeroman];
+ 0x2173 = [fourroman];
+ 0x2174 = [fiveroman];
+ 0x2175 = [sixroman];
+ 0x2176 = [sevenroman];
+ 0x2177 = [eightroman];
+ 0x2178 = [nineroman];
+ 0x2179 = [tenroman];
+ 0x217a = [elevenroman];
+ 0x217b = [twelveroman];
+ 0x2190 = [arrowleft];
+ 0x2191 = [arrowtp, arrowup];
+ 0x2192 = [arrowright];
+ 0x2193 = [arrowbt, arrowdown];
+ 0x2194 = [arrowboth];
+ 0x2195 = [arrowbothv, arrowupdn, arrowvertex];
+ 0x2196 = [arrownorthwest, arrowupleft];
+ 0x2197 = [arrownortheast, arrowupright];
+ 0x2198 = [arrowdownright, arrowsoutheast];
+ 0x2199 = [arrowdownleft, arrowsouthwest];
+ 0x21a8 = [arrowupdnbse, arrowupdownbase];
+ 0x21a9 = [hookleftchar];
+ 0x21aa = [hookrightchar];
+ 0x21b5 = [carriagereturn];
+ 0x21bc = [arrowlefttophalf, harpoonleftbarbup, harpoonleftup];
+ 0x21bd = [arrowleftbothalf, harpoonleftdown];
+ 0x21c0 = [arrowrighttophalf, harpoonrightbarbup, harpoonrightup];
+ 0x21c1 = [arrowrightbothalf, harpoonrightdown];
+ 0x21c4 = [arrowrightoverleft];
+ 0x21c5 = [arrowupleftofdown];
+ 0x21c6 = [arrowleftoverright];
+ 0x21cd = [arrowleftdblstroke];
+ 0x21cf = [arrowrightdblstroke];
+ 0x21d0 = [arrowdblleft, arrowleftdbl];
+ 0x21d1 = [arrowdbltp, arrowdblup];
+ 0x21d2 = [arrowdblright, dblarrowright];
+ 0x21d3 = [arrowdbldown];
+ 0x21d4 = [arrowdblboth, dblarrowleft];
+ 0x21d5 = [arrowdblbothv, arrowdblvertex];
+ 0x21de = [pageup];
+ 0x21df = [pagedown];
+ 0x21e0 = [arrowdashleft];
+ 0x21e1 = [arrowdashup];
+ 0x21e2 = [arrowdashright];
+ 0x21e3 = [arrowdashdown];
+ 0x21e4 = [arrowtableft];
+ 0x21e5 = [arrowtabright];
+ 0x21e6 = [arrowleftwhite];
+ 0x21e7 = [arrowupwhite];
+ 0x21e8 = [arrowrightwhite];
+ 0x21e9 = [arrowdownwhite];
+ 0x21ea = [capslock];
+ 0x2200 = [forall, universal];
+ 0x2202 = [partialdiff];
+ 0x2203 = [existential, thereexists];
+ 0x2205 = [emptyset];
+ 0x2206 = [Delta, increment];
+ 0x2207 = [gradient, nabla];
+ 0x2208 = [element];
+ 0x2209 = [notelement, notelementof];
+ 0x220b = [owner, suchthat];
+ 0x220c = [notcontains];
+ 0x220f = [product, productdisplay, producttext];
+ 0x2210 = [coproductdisplay, coproducttext];
+ 0x2211 = [summation, summationdisplay, summationtext];
+ 0x2212 = [minus];
+ 0x2213 = [minusplus];
+ 0x2215 = [divisionslash, slashbig, slashBig, slashbigg, slashBigg];
+ 0x2217 = [asteriskcentered, asteriskmath];
+ 0x2219 = [bulletoperator];
+ 0x221a = [radical, radicalbig, radicalBig, radicalbigg, radicalBigg, radicalbt];
+ 0x221d = [proportional];
+ 0x221e = [infinity];
+ 0x221f = [orthogonal, rightangle];
+ 0x2220 = [angle];
+ 0x2223 = [divides];
+ 0x2225 = [bardbl, parallel];
+ 0x2226 = [notparallel];
+ 0x2227 = [logicaland];
+ 0x2228 = [logicalor];
+ 0x2229 = [intersection];
+ 0x222a = [union];
+ 0x222b = [integral, integraldisplay, integraltext];
+ 0x222c = [dblintegral];
+ 0x222e = [contintegraldisplay, contintegraltext, contourintegral];
+ 0x2234 = [therefore];
+ 0x2235 = [because];
+ 0x2236 = [ratio];
+ 0x2237 = [proportion];
+ 0x223c = [similar, tildeoperator];
+ 0x223d = [reversedtilde];
+ 0x2240 = [wreathproduct];
+ 0x2243 = [asymptoticallyequal, similarequal];
+ 0x2245 = [approximatelyequal, congruent];
+ 0x2248 = [approxequal];
+ 0x224c = [allequal];
+ 0x224d = [equivasymptotic];
+ 0x2250 = [approaches];
+ 0x2251 = [geometricallyequal];
+ 0x2252 = [approxequalorimage];
+ 0x2253 = [imageorapproximatelyequal];
+ 0x2260 = [notequal];
+ 0x2261 = [equivalence];
+ 0x2262 = [notidentical];
+ 0x2264 = [lessequal];
+ 0x2265 = [greaterequal];
+ 0x2266 = [lessoverequal];
+ 0x2267 = [greateroverequal];
+ 0x226a = [lessmuch, muchless];
+ 0x226b = [greatermuch, muchgreater];
+ 0x226e = [notless];
+ 0x226f = [notgreater];
+ 0x2270 = [notlessnorequal];
+ 0x2271 = [notgreaternorequal];
+ 0x2272 = [lessorequivalent];
+ 0x2273 = [greaterorequivalent];
+ 0x2276 = [lessorgreater];
+ 0x2277 = [greaterorless];
+ 0x2279 = [notgreaternorless];
+ 0x227a = [precedes];
+ 0x227b = [follows, succeeds];
+ 0x227c = [precedesequal];
+ 0x227d = [followsequal];
+ 0x2280 = [notprecedes];
+ 0x2281 = [notsucceeds];
+ 0x2282 = [propersubset, subset];
+ 0x2283 = [propersuperset, superset];
+ 0x2284 = [notsubset];
+ 0x2285 = [notsuperset];
+ 0x2286 = [reflexsubset, subsetorequal];
+ 0x2287 = [reflexsuperset, supersetorequal];
+ 0x228a = [subsetnotequal];
+ 0x228b = [supersetnotequal];
+ 0x228e = [unionmulti, unionmultidisplay, unionmultitext];
+ 0x2291 = [subsetsqequal];
+ 0x2292 = [supersetsqequal];
+ 0x2293 = [intersectionsq];
+ 0x2294 = [unionsq, unionsqdisplay, unionsqtext];
+ 0x2295 = [circleplus, circleplusdisplay, circleplustext, pluscircle];
+ 0x2296 = [circleminus, minuscircle];
+ 0x2297 = [circlemultiply, circlemultiplydisplay, circlemultiplytext, timescircle];
+ 0x2298 = [circledivide];
+ 0x2299 = [circledot, circledotdisplay, circledottext, circleot];
+ 0x22a2 = [turnstileleft];
+ 0x22a3 = [tackleft, turnstileright];
+ 0x22a4 = [latticetop, tackdown];
+ 0x22a5 = [perpendicular];
+ 0x22bf = [righttriangle];
+ 0x22c0 = [logicalanddisplay, logicalandtext];
+ 0x22c1 = [logicalordisplay, logicalortext];
+ 0x22c2 = [intersectiondisplay, intersectiontext];
+ 0x22c3 = [uniondisplay, uniontext];
+ 0x22c4 = [diamondmath];
+ 0x22c5 = [dotmath];
+ 0x22c6 = [star];
+ 0x22ce = [curlyor];
+ 0x22cf = [curlyand];
+ 0x22da = [lessequalorgreater];
+ 0x22db = [greaterequalorless];
+ 0x22ee = [ellipsisvertical];
+ 0x2302 = [house];
+ 0x2303 = [control];
+ 0x2305 = [projective];
+ 0x2308 = [ceilingleft, ceilingleftbig, ceilingleftBig, ceilingleftbigg, ceilingleftBigg];
+ 0x2309 = [ceilingright, ceilingrightbig, ceilingrightBig, ceilingrightbigg, ceilingrightBigg];
+ 0x230a = [floorleft, floorleftbig, floorleftBig, floorleftbigg, floorleftBigg];
+ 0x230b = [floorright, floorrightbig, floorrightBig, floorrightbigg, floorrightBigg];
+ 0x2310 = [logicalnotreversed, revlogicalnot];
+ 0x2312 = [arc];
+ 0x2318 = [propellor];
+ 0x2320 = [integraltop, integraltp];
+ 0x2321 = [integralbottom, integralbt];
+ 0x2322 = [slurabove];
+ 0x2323 = [slurbelow];
+ 0x2325 = [option];
+ 0x2326 = [deleteright];
+ 0x2327 = [clear];
+ 0x2329 = [angleleft, angleleftbig, angleleftBig, angleleftbigg, angleleftBigg];
+ 0x232a = [angleright, anglerightbig, anglerightBig, anglerightbigg, anglerightBigg];
+ 0x232b = [deleteleft];
+ 0x2423 = [blank, visiblespace, visualspace];
+ 0x2460 = [onecircle];
+ 0x2461 = [twocircle];
+ 0x2462 = [threecircle];
+ 0x2463 = [fourcircle];
+ 0x2464 = [fivecircle];
+ 0x2465 = [sixcircle];
+ 0x2466 = [sevencircle];
+ 0x2467 = [eightcircle];
+ 0x2468 = [ninecircle];
+ 0x2469 = [tencircle];
+ 0x246a = [elevencircle];
+ 0x246b = [twelvecircle];
+ 0x246c = [thirteencircle];
+ 0x246d = [fourteencircle];
+ 0x246e = [fifteencircle];
+ 0x246f = [sixteencircle];
+ 0x2470 = [seventeencircle];
+ 0x2471 = [eighteencircle];
+ 0x2472 = [nineteencircle];
+ 0x2473 = [twentycircle];
+ 0x2474 = [oneparen];
+ 0x2475 = [twoparen];
+ 0x2476 = [threeparen];
+ 0x2477 = [fourparen];
+ 0x2478 = [fiveparen];
+ 0x2479 = [sixparen];
+ 0x247a = [sevenparen];
+ 0x247b = [eightparen];
+ 0x247c = [nineparen];
+ 0x247d = [tenparen];
+ 0x247e = [elevenparen];
+ 0x247f = [twelveparen];
+ 0x2480 = [thirteenparen];
+ 0x2481 = [fourteenparen];
+ 0x2482 = [fifteenparen];
+ 0x2483 = [sixteenparen];
+ 0x2484 = [seventeenparen];
+ 0x2485 = [eighteenparen];
+ 0x2486 = [nineteenparen];
+ 0x2487 = [twentyparen];
+ 0x2488 = [oneperiod];
+ 0x2489 = [twoperiod];
+ 0x248a = [threeperiod];
+ 0x248b = [fourperiod];
+ 0x248c = [fiveperiod];
+ 0x248d = [sixperiod];
+ 0x248e = [sevenperiod];
+ 0x248f = [eightperiod];
+ 0x2490 = [nineperiod];
+ 0x2491 = [tenperiod];
+ 0x2492 = [elevenperiod];
+ 0x2493 = [twelveperiod];
+ 0x2494 = [thirteenperiod];
+ 0x2495 = [fourteenperiod];
+ 0x2496 = [fifteenperiod];
+ 0x2497 = [sixteenperiod];
+ 0x2498 = [seventeenperiod];
+ 0x2499 = [eighteenperiod];
+ 0x249a = [nineteenperiod];
+ 0x249b = [twentyperiod];
+ 0x249c = [aparen];
+ 0x249d = [bparen];
+ 0x249e = [cparen];
+ 0x249f = [dparen];
+ 0x24a0 = [eparen];
+ 0x24a1 = [fparen];
+ 0x24a2 = [gparen];
+ 0x24a3 = [hparen];
+ 0x24a4 = [iparen];
+ 0x24a5 = [jparen];
+ 0x24a6 = [kparen];
+ 0x24a7 = [lparen];
+ 0x24a8 = [mparen];
+ 0x24a9 = [nparen];
+ 0x24aa = [oparen];
+ 0x24ab = [pparen];
+ 0x24ac = [qparen];
+ 0x24ad = [rparen];
+ 0x24ae = [sparen];
+ 0x24af = [tparen];
+ 0x24b0 = [uparen];
+ 0x24b1 = [vparen];
+ 0x24b2 = [wparen];
+ 0x24b3 = [xparen];
+ 0x24b4 = [yparen];
+ 0x24b5 = [zparen];
+ 0x24b6 = [Acircle];
+ 0x24b7 = [Bcircle];
+ 0x24b8 = [Ccircle];
+ 0x24b9 = [Dcircle];
+ 0x24ba = [Ecircle];
+ 0x24bb = [Fcircle];
+ 0x24bc = [Gcircle];
+ 0x24bd = [Hcircle];
+ 0x24be = [Icircle];
+ 0x24bf = [Jcircle];
+ 0x24c0 = [Kcircle];
+ 0x24c1 = [Lcircle];
+ 0x24c2 = [Mcircle];
+ 0x24c3 = [Ncircle];
+ 0x24c4 = [Ocircle];
+ 0x24c5 = [Pcircle];
+ 0x24c6 = [Qcircle];
+ 0x24c7 = [Rcircle];
+ 0x24c8 = [Scircle];
+ 0x24c9 = [Tcircle];
+ 0x24ca = [Ucircle];
+ 0x24cb = [Vcircle];
+ 0x24cc = [Wcircle];
+ 0x24cd = [Xcircle];
+ 0x24ce = [Ycircle];
+ 0x24cf = [Zcircle];
+ 0x24d0 = [acircle];
+ 0x24d1 = [bcircle];
+ 0x24d2 = [ccircle];
+ 0x24d3 = [dcircle];
+ 0x24d4 = [ecircle];
+ 0x24d5 = [fcircle];
+ 0x24d6 = [gcircle];
+ 0x24d7 = [hcircle];
+ 0x24d8 = [icircle];
+ 0x24d9 = [jcircle];
+ 0x24da = [kcircle];
+ 0x24db = [lcircle];
+ 0x24dc = [mcircle];
+ 0x24dd = [ncircle];
+ 0x24de = [ocircle];
+ 0x24df = [pcircle];
+ 0x24e0 = [qcircle];
+ 0x24e1 = [rcircle];
+ 0x24e2 = [scircle];
+ 0x24e3 = [tcircle];
+ 0x24e4 = [ucircle];
+ 0x24e5 = [vcircle];
+ 0x24e6 = [wcircle];
+ 0x24e7 = [xcircle];
+ 0x24e8 = [ycircle];
+ 0x24e9 = [zcircle];
+ 0x2500 = [SF100000];
+ 0x2502 = [SF110000];
+ 0x250c = [SF010000];
+ 0x2510 = [SF030000];
+ 0x2514 = [SF020000];
+ 0x2518 = [SF040000];
+ 0x251c = [SF080000];
+ 0x2524 = [SF090000];
+ 0x252c = [SF060000];
+ 0x2534 = [SF070000];
+ 0x253c = [SF050000];
+ 0x2550 = [SF430000];
+ 0x2551 = [SF240000];
+ 0x2552 = [SF510000];
+ 0x2553 = [SF520000];
+ 0x2554 = [SF390000];
+ 0x2555 = [SF220000];
+ 0x2556 = [SF210000];
+ 0x2557 = [SF250000];
+ 0x2558 = [SF500000];
+ 0x2559 = [SF490000];
+ 0x255a = [SF380000];
+ 0x255b = [SF280000];
+ 0x255c = [SF270000];
+ 0x255d = [SF260000];
+ 0x255e = [SF360000];
+ 0x255f = [SF370000];
+ 0x2560 = [SF420000];
+ 0x2561 = [SF190000];
+ 0x2562 = [SF200000];
+ 0x2563 = [SF230000];
+ 0x2564 = [SF470000];
+ 0x2565 = [SF480000];
+ 0x2566 = [SF410000];
+ 0x2567 = [SF450000];
+ 0x2568 = [SF460000];
+ 0x2569 = [SF400000];
+ 0x256a = [SF540000];
+ 0x256b = [SF530000];
+ 0x256c = [SF440000];
+ 0x2580 = [upblock];
+ 0x2584 = [dnblock];
+ 0x2588 = [block];
+ 0x258c = [lfblock];
+ 0x2590 = [rtblock];
+ 0x2591 = [ltshade, shadelight];
+ 0x2592 = [shade, shademedium];
+ 0x2593 = [dkshade, shadedark];
+ 0x25a0 = [blacksquare, filledbox];
+ 0x25a1 = [H22073, whitesquare];
+ 0x25a3 = [squarewhitewithsmallblack];
+ 0x25a4 = [squarehorizontalfill];
+ 0x25a5 = [squareverticalfill];
+ 0x25a6 = [squareorthogonalcrosshatchfill];
+ 0x25a7 = [squareupperlefttolowerrightfill];
+ 0x25a8 = [squareupperrighttolowerleftfill];
+ 0x25a9 = [squarediagonalcrosshatchfill];
+ 0x25aa = [blacksmallsquare, H18543];
+ 0x25ab = [H18551, whitesmallsquare];
+ 0x25ac = [blackrectangle, filledrect];
+ 0x25b2 = [blackuppointingtriangle, triagup];
+ 0x25b3 = [triangle, whiteuppointingtriangle];
+ 0x25b4 = [blackuppointingsmalltriangle];
+ 0x25b5 = [whiteuppointingsmalltriangle];
+ 0x25b6 = [blackrightpointingtriangle];
+ 0x25b7 = [whiterightpointingtriangle];
+ 0x25b9 = [triangleleft, whiterightpointingsmalltriangle];
+ 0x25ba = [blackrightpointingpointer, triagrt];
+ 0x25bc = [blackdownpointingtriangle, triagdn];
+ 0x25bd = [triangleinv, whitedownpointingtriangle];
+ 0x25bf = [whitedownpointingsmalltriangle];
+ 0x25c0 = [blackleftpointingtriangle];
+ 0x25c1 = [whiteleftpointingtriangle];
+ 0x25c3 = [triangleright, whiteleftpointingsmalltriangle];
+ 0x25c4 = [blackleftpointingpointer, triaglf];
+ 0x25c6 = [blackdiamond];
+ 0x25c7 = [whitediamond];
+ 0x25c8 = [whitediamondcontainingblacksmalldiamond];
+ 0x25c9 = [fisheye];
+ 0x25ca = [lozenge];
+ 0x25cb = [circle, whitecircle];
+ 0x25cc = [dottedcircle];
+ 0x25ce = [bullseye];
+ 0x25cf = [blackcircle, H18533];
+ 0x25d0 = [circlewithlefthalfblack];
+ 0x25d1 = [circlewithrighthalfblack];
+ 0x25d8 = [bulletinverse, invbullet];
+ 0x25d9 = [invcircle, whitecircleinverse];
+ 0x25e2 = [blacklowerrighttriangle];
+ 0x25e3 = [blacklowerlefttriangle];
+ 0x25e4 = [blackupperlefttriangle];
+ 0x25e5 = [blackupperrighttriangle];
+ 0x25e6 = [openbullet, whitebullet];
+ 0x25ef = [largecircle];
+ 0x2605 = [blackstar];
+ 0x2606 = [whitestar];
+ 0x260e = [telephoneblack];
+ 0x260f = [whitetelephone];
+ 0x261c = [pointingindexleftwhite];
+ 0x261d = [pointingindexupwhite];
+ 0x261e = [pointingindexrightwhite];
+ 0x261f = [pointingindexdownwhite];
+ 0x262f = [yinyang];
+ 0x263a = [smileface, whitesmilingface];
+ 0x263b = [blacksmilingface, invsmileface];
+ 0x263c = [compass, sun];
+ 0x2640 = [female, venus];
+ 0x2641 = [earth];
+ 0x2642 = [male, mars];
+ 0x2660 = [spade, spadesuitblack];
+ 0x2661 = [heart, heartsuitwhite];
+ 0x2662 = [diamond, diamondsuitwhite];
+ 0x2663 = [club, clubsuitblack];
+ 0x2664 = [spadesuitwhite];
+ 0x2665 = [heart2, heartsuitblack];
+ 0x2666 = [diamond2];
+ 0x2667 = [clubsuitwhite];
+ 0x2668 = [hotsprings];
+ 0x2669 = [quarternote];
+ 0x266a = [musicalnote];
+ 0x266b = [eighthnotebeamed, musicalnotedbl];
+ 0x266c = [beamedsixteenthnotes];
+ 0x266d = [flat, musicflatsign];
+ 0x266e = [natural];
+ 0x266f = [musicsharpsign, sharp];
+ 0x2713 = [checkmark];
+ 0x278a = [onecircleinversesansserif];
+ 0x278b = [twocircleinversesansserif];
+ 0x278c = [threecircleinversesansserif];
+ 0x278d = [fourcircleinversesansserif];
+ 0x278e = [fivecircleinversesansserif];
+ 0x278f = [sixcircleinversesansserif];
+ 0x2790 = [sevencircleinversesansserif];
+ 0x2791 = [eightcircleinversesansserif];
+ 0x2792 = [ninecircleinversesansserif];
+ 0x279e = [arrowrightheavy];
+ 0x27e6 = [dblbracketleft];
+ 0x27e7 = [dblbracketright];
+ 0x27e8 = [angbracketleft];
+ 0x27e9 = [angbracketright];
+ 0x2a3f = [coproduct];
+ 0x3000 = [ideographicspace];
+ 0x3001 = [ideographiccomma];
+ 0x3002 = [ideographicperiod];
+ 0x3003 = [dittomark];
+ 0x3004 = [jis];
+ 0x3005 = [ideographiciterationmark];
+ 0x3006 = [ideographicclose];
+ 0x3007 = [ideographiczero];
+ 0x3008 = [anglebracketleft];
+ 0x3009 = [anglebracketright];
+ 0x300a = [dblanglebracketleft];
+ 0x300b = [dblanglebracketright];
+ 0x300c = [cornerbracketleft];
+ 0x300d = [cornerbracketright];
+ 0x300e = [whitecornerbracketleft];
+ 0x300f = [whitecornerbracketright];
+ 0x3010 = [blacklenticularbracketleft];
+ 0x3011 = [blacklenticularbracketright];
+ 0x3012 = [postalmark];
+ 0x3013 = [getamark];
+ 0x3014 = [tortoiseshellbracketleft];
+ 0x3015 = [tortoiseshellbracketright];
+ 0x3016 = [whitelenticularbracketleft];
+ 0x3017 = [whitelenticularbracketright];
+ 0x3018 = [whitetortoiseshellbracketleft];
+ 0x3019 = [whitetortoiseshellbracketright];
+ 0x301c = [wavedash];
+ 0x301d = [quotedblprimereversed];
+ 0x301e = [quotedblprime];
+ 0x3020 = [postalmarkface];
+ 0x3021 = [onehangzhou];
+ 0x3022 = [twohangzhou];
+ 0x3023 = [threehangzhou];
+ 0x3024 = [fourhangzhou];
+ 0x3025 = [fivehangzhou];
+ 0x3026 = [sixhangzhou];
+ 0x3027 = [sevenhangzhou];
+ 0x3028 = [eighthangzhou];
+ 0x3029 = [ninehangzhou];
+ 0x3036 = [circlepostalmark];
+ 0x3041 = [asmallhiragana];
+ 0x3042 = [ahiragana];
+ 0x3043 = [ismallhiragana];
+ 0x3044 = [ihiragana];
+ 0x3045 = [usmallhiragana];
+ 0x3046 = [uhiragana];
+ 0x3047 = [esmallhiragana];
+ 0x3048 = [ehiragana];
+ 0x3049 = [osmallhiragana];
+ 0x304a = [ohiragana];
+ 0x304b = [kahiragana];
+ 0x304c = [gahiragana];
+ 0x304d = [kihiragana];
+ 0x304e = [gihiragana];
+ 0x304f = [kuhiragana];
+ 0x3050 = [guhiragana];
+ 0x3051 = [kehiragana];
+ 0x3052 = [gehiragana];
+ 0x3053 = [kohiragana];
+ 0x3054 = [gohiragana];
+ 0x3055 = [sahiragana];
+ 0x3056 = [zahiragana];
+ 0x3057 = [sihiragana];
+ 0x3058 = [zihiragana];
+ 0x3059 = [suhiragana];
+ 0x305a = [zuhiragana];
+ 0x305b = [sehiragana];
+ 0x305c = [zehiragana];
+ 0x305d = [sohiragana];
+ 0x305e = [zohiragana];
+ 0x305f = [tahiragana];
+ 0x3060 = [dahiragana];
+ 0x3061 = [tihiragana];
+ 0x3062 = [dihiragana];
+ 0x3063 = [tusmallhiragana];
+ 0x3064 = [tuhiragana];
+ 0x3065 = [duhiragana];
+ 0x3066 = [tehiragana];
+ 0x3067 = [dehiragana];
+ 0x3068 = [tohiragana];
+ 0x3069 = [dohiragana];
+ 0x306a = [nahiragana];
+ 0x306b = [nihiragana];
+ 0x306c = [nuhiragana];
+ 0x306d = [nehiragana];
+ 0x306e = [nohiragana];
+ 0x306f = [hahiragana];
+ 0x3070 = [bahiragana];
+ 0x3071 = [pahiragana];
+ 0x3072 = [hihiragana];
+ 0x3073 = [bihiragana];
+ 0x3074 = [pihiragana];
+ 0x3075 = [huhiragana];
+ 0x3076 = [buhiragana];
+ 0x3077 = [puhiragana];
+ 0x3078 = [hehiragana];
+ 0x3079 = [behiragana];
+ 0x307a = [pehiragana];
+ 0x307b = [hohiragana];
+ 0x307c = [bohiragana];
+ 0x307d = [pohiragana];
+ 0x307e = [mahiragana];
+ 0x307f = [mihiragana];
+ 0x3080 = [muhiragana];
+ 0x3081 = [mehiragana];
+ 0x3082 = [mohiragana];
+ 0x3083 = [yasmallhiragana];
+ 0x3084 = [yahiragana];
+ 0x3085 = [yusmallhiragana];
+ 0x3086 = [yuhiragana];
+ 0x3087 = [yosmallhiragana];
+ 0x3088 = [yohiragana];
+ 0x3089 = [rahiragana];
+ 0x308a = [rihiragana];
+ 0x308b = [ruhiragana];
+ 0x308c = [rehiragana];
+ 0x308d = [rohiragana];
+ 0x308e = [wasmallhiragana];
+ 0x308f = [wahiragana];
+ 0x3090 = [wihiragana];
+ 0x3091 = [wehiragana];
+ 0x3092 = [wohiragana];
+ 0x3093 = [nhiragana];
+ 0x3094 = [vuhiragana];
+ 0x309b = [voicedmarkkana];
+ 0x309c = [semivoicedmarkkana];
+ 0x309d = [iterationhiragana];
+ 0x309e = [voicediterationhiragana];
+ 0x30a1 = [asmallkatakana];
+ 0x30a2 = [akatakana];
+ 0x30a3 = [ismallkatakana];
+ 0x30a4 = [ikatakana];
+ 0x30a5 = [usmallkatakana];
+ 0x30a6 = [ukatakana];
+ 0x30a7 = [esmallkatakana];
+ 0x30a8 = [ekatakana];
+ 0x30a9 = [osmallkatakana];
+ 0x30aa = [okatakana];
+ 0x30ab = [kakatakana];
+ 0x30ac = [gakatakana];
+ 0x30ad = [kikatakana];
+ 0x30ae = [gikatakana];
+ 0x30af = [kukatakana];
+ 0x30b0 = [gukatakana];
+ 0x30b1 = [kekatakana];
+ 0x30b2 = [gekatakana];
+ 0x30b3 = [kokatakana];
+ 0x30b4 = [gokatakana];
+ 0x30b5 = [sakatakana];
+ 0x30b6 = [zakatakana];
+ 0x30b7 = [sikatakana];
+ 0x30b8 = [zikatakana];
+ 0x30b9 = [sukatakana];
+ 0x30ba = [zukatakana];
+ 0x30bb = [sekatakana];
+ 0x30bc = [zekatakana];
+ 0x30bd = [sokatakana];
+ 0x30be = [zokatakana];
+ 0x30bf = [takatakana];
+ 0x30c0 = [dakatakana];
+ 0x30c1 = [tikatakana];
+ 0x30c2 = [dikatakana];
+ 0x30c3 = [tusmallkatakana];
+ 0x30c4 = [tukatakana];
+ 0x30c5 = [dukatakana];
+ 0x30c6 = [tekatakana];
+ 0x30c7 = [dekatakana];
+ 0x30c8 = [tokatakana];
+ 0x30c9 = [dokatakana];
+ 0x30ca = [nakatakana];
+ 0x30cb = [nikatakana];
+ 0x30cc = [nukatakana];
+ 0x30cd = [nekatakana];
+ 0x30ce = [nokatakana];
+ 0x30cf = [hakatakana];
+ 0x30d0 = [bakatakana];
+ 0x30d1 = [pakatakana];
+ 0x30d2 = [hikatakana];
+ 0x30d3 = [bikatakana];
+ 0x30d4 = [pikatakana];
+ 0x30d5 = [hukatakana];
+ 0x30d6 = [bukatakana];
+ 0x30d7 = [pukatakana];
+ 0x30d8 = [hekatakana];
+ 0x30d9 = [bekatakana];
+ 0x30da = [pekatakana];
+ 0x30db = [hokatakana];
+ 0x30dc = [bokatakana];
+ 0x30dd = [pokatakana];
+ 0x30de = [makatakana];
+ 0x30df = [mikatakana];
+ 0x30e0 = [mukatakana];
+ 0x30e1 = [mekatakana];
+ 0x30e2 = [mokatakana];
+ 0x30e3 = [yasmallkatakana];
+ 0x30e4 = [yakatakana];
+ 0x30e5 = [yusmallkatakana];
+ 0x30e6 = [yukatakana];
+ 0x30e7 = [yosmallkatakana];
+ 0x30e8 = [yokatakana];
+ 0x30e9 = [rakatakana];
+ 0x30ea = [rikatakana];
+ 0x30eb = [rukatakana];
+ 0x30ec = [rekatakana];
+ 0x30ed = [rokatakana];
+ 0x30ee = [wasmallkatakana];
+ 0x30ef = [wakatakana];
+ 0x30f0 = [wikatakana];
+ 0x30f1 = [wekatakana];
+ 0x30f2 = [wokatakana];
+ 0x30f3 = [nkatakana];
+ 0x30f4 = [vukatakana];
+ 0x30f5 = [kasmallkatakana];
+ 0x30f6 = [kesmallkatakana];
+ 0x30f7 = [vakatakana];
+ 0x30f8 = [vikatakana];
+ 0x30f9 = [vekatakana];
+ 0x30fa = [vokatakana];
+ 0x30fb = [dotkatakana];
+ 0x30fc = [prolongedkana];
+ 0x30fd = [iterationkatakana];
+ 0x30fe = [voicediterationkatakana];
+ 0x3105 = [bbopomofo];
+ 0x3106 = [pbopomofo];
+ 0x3107 = [mbopomofo];
+ 0x3108 = [fbopomofo];
+ 0x3109 = [dbopomofo];
+ 0x310a = [tbopomofo];
+ 0x310b = [nbopomofo];
+ 0x310c = [lbopomofo];
+ 0x310d = [gbopomofo];
+ 0x310e = [kbopomofo];
+ 0x310f = [hbopomofo];
+ 0x3110 = [jbopomofo];
+ 0x3111 = [qbopomofo];
+ 0x3112 = [xbopomofo];
+ 0x3113 = [zhbopomofo];
+ 0x3114 = [chbopomofo];
+ 0x3115 = [shbopomofo];
+ 0x3116 = [rbopomofo];
+ 0x3117 = [zbopomofo];
+ 0x3118 = [cbopomofo];
+ 0x3119 = [sbopomofo];
+ 0x311a = [abopomofo];
+ 0x311b = [obopomofo];
+ 0x311c = [ebopomofo];
+ 0x311d = [ehbopomofo];
+ 0x311e = [aibopomofo];
+ 0x311f = [eibopomofo];
+ 0x3120 = [aubopomofo];
+ 0x3121 = [oubopomofo];
+ 0x3122 = [anbopomofo];
+ 0x3123 = [enbopomofo];
+ 0x3124 = [angbopomofo];
+ 0x3125 = [engbopomofo];
+ 0x3126 = [erbopomofo];
+ 0x3127 = [ibopomofo];
+ 0x3128 = [ubopomofo];
+ 0x3129 = [iubopomofo];
+ 0x3131 = [kiyeokkorean];
+ 0x3132 = [ssangkiyeokkorean];
+ 0x3133 = [kiyeoksioskorean];
+ 0x3134 = [nieunkorean];
+ 0x3135 = [nieuncieuckorean];
+ 0x3136 = [nieunhieuhkorean];
+ 0x3137 = [tikeutkorean];
+ 0x3138 = [ssangtikeutkorean];
+ 0x3139 = [rieulkorean];
+ 0x313a = [rieulkiyeokkorean];
+ 0x313b = [rieulmieumkorean];
+ 0x313c = [rieulpieupkorean];
+ 0x313d = [rieulsioskorean];
+ 0x313e = [rieulthieuthkorean];
+ 0x313f = [rieulphieuphkorean];
+ 0x3140 = [rieulhieuhkorean];
+ 0x3141 = [mieumkorean];
+ 0x3142 = [pieupkorean];
+ 0x3143 = [ssangpieupkorean];
+ 0x3144 = [pieupsioskorean];
+ 0x3145 = [sioskorean];
+ 0x3146 = [ssangsioskorean];
+ 0x3147 = [ieungkorean];
+ 0x3148 = [cieuckorean];
+ 0x3149 = [ssangcieuckorean];
+ 0x314a = [chieuchkorean];
+ 0x314b = [khieukhkorean];
+ 0x314c = [thieuthkorean];
+ 0x314d = [phieuphkorean];
+ 0x314e = [hieuhkorean];
+ 0x314f = [akorean];
+ 0x3150 = [aekorean];
+ 0x3151 = [yakorean];
+ 0x3152 = [yaekorean];
+ 0x3153 = [eokorean];
+ 0x3154 = [ekorean];
+ 0x3155 = [yeokorean];
+ 0x3156 = [yekorean];
+ 0x3157 = [okorean];
+ 0x3158 = [wakorean];
+ 0x3159 = [waekorean];
+ 0x315a = [oekorean];
+ 0x315b = [yokorean];
+ 0x315c = [ukorean];
+ 0x315d = [weokorean];
+ 0x315e = [wekorean];
+ 0x315f = [wikorean];
+ 0x3160 = [yukorean];
+ 0x3161 = [eukorean];
+ 0x3162 = [yikorean];
+ 0x3163 = [ikorean];
+ 0x3164 = [hangulfiller];
+ 0x3165 = [ssangnieunkorean];
+ 0x3166 = [nieuntikeutkorean];
+ 0x3167 = [nieunsioskorean];
+ 0x3168 = [nieunpansioskorean];
+ 0x3169 = [rieulkiyeoksioskorean];
+ 0x316a = [rieultikeutkorean];
+ 0x316b = [rieulpieupsioskorean];
+ 0x316c = [rieulpansioskorean];
+ 0x316d = [rieulyeorinhieuhkorean];
+ 0x316e = [mieumpieupkorean];
+ 0x316f = [mieumsioskorean];
+ 0x3170 = [mieumpansioskorean];
+ 0x3171 = [kapyeounmieumkorean];
+ 0x3172 = [pieupkiyeokkorean];
+ 0x3173 = [pieuptikeutkorean];
+ 0x3174 = [pieupsioskiyeokkorean];
+ 0x3175 = [pieupsiostikeutkorean];
+ 0x3176 = [pieupcieuckorean];
+ 0x3177 = [pieupthieuthkorean];
+ 0x3178 = [kapyeounpieupkorean];
+ 0x3179 = [kapyeounssangpieupkorean];
+ 0x317a = [sioskiyeokkorean];
+ 0x317b = [siosnieunkorean];
+ 0x317c = [siostikeutkorean];
+ 0x317d = [siospieupkorean];
+ 0x317e = [sioscieuckorean];
+ 0x317f = [pansioskorean];
+ 0x3180 = [ssangieungkorean];
+ 0x3181 = [yesieungkorean];
+ 0x3182 = [yesieungsioskorean];
+ 0x3183 = [yesieungpansioskorean];
+ 0x3184 = [kapyeounphieuphkorean];
+ 0x3185 = [ssanghieuhkorean];
+ 0x3186 = [yeorinhieuhkorean];
+ 0x3187 = [yoyakorean];
+ 0x3188 = [yoyaekorean];
+ 0x3189 = [yoikorean];
+ 0x318a = [yuyeokorean];
+ 0x318b = [yuyekorean];
+ 0x318c = [yuikorean];
+ 0x318d = [araeakorean];
+ 0x318e = [araeaekorean];
+ 0x3200 = [kiyeokparenkorean];
+ 0x3201 = [nieunparenkorean];
+ 0x3202 = [tikeutparenkorean];
+ 0x3203 = [rieulparenkorean];
+ 0x3204 = [mieumparenkorean];
+ 0x3205 = [pieupparenkorean];
+ 0x3206 = [siosparenkorean];
+ 0x3207 = [ieungparenkorean];
+ 0x3208 = [cieucparenkorean];
+ 0x3209 = [chieuchparenkorean];
+ 0x320a = [khieukhparenkorean];
+ 0x320b = [thieuthparenkorean];
+ 0x320c = [phieuphparenkorean];
+ 0x320d = [hieuhparenkorean];
+ 0x320e = [kiyeokaparenkorean];
+ 0x320f = [nieunaparenkorean];
+ 0x3210 = [tikeutaparenkorean];
+ 0x3211 = [rieulaparenkorean];
+ 0x3212 = [mieumaparenkorean];
+ 0x3213 = [pieupaparenkorean];
+ 0x3214 = [siosaparenkorean];
+ 0x3215 = [ieungaparenkorean];
+ 0x3216 = [cieucaparenkorean];
+ 0x3217 = [chieuchaparenkorean];
+ 0x3218 = [khieukhaparenkorean];
+ 0x3219 = [thieuthaparenkorean];
+ 0x321a = [phieuphaparenkorean];
+ 0x321b = [hieuhaparenkorean];
+ 0x321c = [cieucuparenkorean];
+ 0x3220 = [oneideographicparen];
+ 0x3221 = [twoideographicparen];
+ 0x3222 = [threeideographicparen];
+ 0x3223 = [fourideographicparen];
+ 0x3224 = [fiveideographicparen];
+ 0x3225 = [sixideographicparen];
+ 0x3226 = [sevenideographicparen];
+ 0x3227 = [eightideographicparen];
+ 0x3228 = [nineideographicparen];
+ 0x3229 = [tenideographicparen];
+ 0x322a = [ideographicmoonparen];
+ 0x322b = [ideographicfireparen];
+ 0x322c = [ideographicwaterparen];
+ 0x322d = [ideographicwoodparen];
+ 0x322e = [ideographicmetalparen];
+ 0x322f = [ideographicearthparen];
+ 0x3230 = [ideographicsunparen];
+ 0x3231 = [ideographicstockparen];
+ 0x3232 = [ideographichaveparen];
+ 0x3233 = [ideographicsocietyparen];
+ 0x3234 = [ideographicnameparen];
+ 0x3235 = [ideographicspecialparen];
+ 0x3236 = [ideographicfinancialparen];
+ 0x3237 = [ideographiccongratulationparen];
+ 0x3238 = [ideographiclaborparen];
+ 0x3239 = [ideographicrepresentparen];
+ 0x323a = [ideographiccallparen];
+ 0x323b = [ideographicstudyparen];
+ 0x323c = [ideographicsuperviseparen];
+ 0x323d = [ideographicenterpriseparen];
+ 0x323e = [ideographicresourceparen];
+ 0x323f = [ideographicallianceparen];
+ 0x3240 = [ideographicfestivalparen];
+ 0x3242 = [ideographicselfparen];
+ 0x3243 = [ideographicreachparen];
+ 0x3260 = [kiyeokcirclekorean];
+ 0x3261 = [nieuncirclekorean];
+ 0x3262 = [tikeutcirclekorean];
+ 0x3263 = [rieulcirclekorean];
+ 0x3264 = [mieumcirclekorean];
+ 0x3265 = [pieupcirclekorean];
+ 0x3266 = [sioscirclekorean];
+ 0x3267 = [ieungcirclekorean];
+ 0x3268 = [cieuccirclekorean];
+ 0x3269 = [chieuchcirclekorean];
+ 0x326a = [khieukhcirclekorean];
+ 0x326b = [thieuthcirclekorean];
+ 0x326c = [phieuphcirclekorean];
+ 0x326d = [hieuhcirclekorean];
+ 0x326e = [kiyeokacirclekorean];
+ 0x326f = [nieunacirclekorean];
+ 0x3270 = [tikeutacirclekorean];
+ 0x3271 = [rieulacirclekorean];
+ 0x3272 = [mieumacirclekorean];
+ 0x3273 = [pieupacirclekorean];
+ 0x3274 = [siosacirclekorean];
+ 0x3275 = [ieungacirclekorean];
+ 0x3276 = [cieucacirclekorean];
+ 0x3277 = [chieuchacirclekorean];
+ 0x3278 = [khieukhacirclekorean];
+ 0x3279 = [thieuthacirclekorean];
+ 0x327a = [phieuphacirclekorean];
+ 0x327b = [hieuhacirclekorean];
+ 0x327f = [koreanstandardsymbol];
+ 0x328a = [ideographmooncircle];
+ 0x328b = [ideographfirecircle];
+ 0x328c = [ideographwatercircle];
+ 0x328d = [ideographwoodcircle];
+ 0x328e = [ideographmetalcircle];
+ 0x328f = [ideographearthcircle];
+ 0x3290 = [ideographsuncircle];
+ 0x3294 = [ideographnamecircle];
+ 0x3296 = [ideographicfinancialcircle];
+ 0x3298 = [ideographiclaborcircle];
+ 0x3299 = [ideographicsecretcircle];
+ 0x329d = [ideographicexcellentcircle];
+ 0x329e = [ideographicprintcircle];
+ 0x32a3 = [ideographiccorrectcircle];
+ 0x32a4 = [ideographichighcircle];
+ 0x32a5 = [ideographiccentrecircle];
+ 0x32a6 = [ideographiclowcircle];
+ 0x32a7 = [ideographicleftcircle];
+ 0x32a8 = [ideographicrightcircle];
+ 0x32a9 = [ideographicmedicinecircle];
+ 0x3300 = [apaatosquare];
+ 0x3303 = [aarusquare];
+ 0x3305 = [intisquare];
+ 0x330d = [karoriisquare];
+ 0x3314 = [kirosquare];
+ 0x3315 = [kiroguramusquare];
+ 0x3316 = [kiromeetorusquare];
+ 0x3318 = [guramusquare];
+ 0x331e = [kooposquare];
+ 0x3322 = [sentisquare];
+ 0x3323 = [sentosquare];
+ 0x3326 = [dorusquare];
+ 0x3327 = [tonsquare];
+ 0x332a = [haitusquare];
+ 0x332b = [paasentosquare];
+ 0x3331 = [birusquare];
+ 0x3333 = [huiitosquare];
+ 0x3336 = [hekutaarusquare];
+ 0x3339 = [herutusquare];
+ 0x333b = [peezisquare];
+ 0x3342 = [hoonsquare];
+ 0x3347 = [mansyonsquare];
+ 0x3349 = [mirisquare];
+ 0x334a = [miribaarusquare];
+ 0x334d = [meetorusquare];
+ 0x334e = [yaadosquare];
+ 0x3351 = [rittorusquare];
+ 0x3357 = [wattosquare];
+ 0x337b = [heiseierasquare];
+ 0x337c = [syouwaerasquare];
+ 0x337d = [taisyouerasquare];
+ 0x337e = [meizierasquare];
+ 0x337f = [corporationsquare];
+ 0x3380 = [paampssquare];
+ 0x3381 = [nasquare];
+ 0x3382 = [muasquare];
+ 0x3383 = [masquare];
+ 0x3384 = [kasquare];
+ 0x3385 = [KBsquare];
+ 0x3386 = [MBsquare];
+ 0x3387 = [GBsquare];
+ 0x3388 = [calsquare];
+ 0x3389 = [kcalsquare];
+ 0x338a = [pfsquare];
+ 0x338b = [nfsquare];
+ 0x338c = [mufsquare];
+ 0x338d = [mugsquare];
+ 0x338e = [squaremg];
+ 0x338f = [squarekg];
+ 0x3390 = [Hzsquare];
+ 0x3391 = [khzsquare];
+ 0x3392 = [mhzsquare];
+ 0x3393 = [ghzsquare];
+ 0x3394 = [thzsquare];
+ 0x3395 = [mulsquare];
+ 0x3396 = [mlsquare];
+ 0x3397 = [dlsquare];
+ 0x3398 = [klsquare];
+ 0x3399 = [fmsquare];
+ 0x339a = [nmsquare];
+ 0x339b = [mumsquare];
+ 0x339c = [squaremm];
+ 0x339d = [squarecm];
+ 0x339e = [squarekm];
+ 0x339f = [mmsquaredsquare];
+ 0x33a0 = [cmsquaredsquare];
+ 0x33a1 = [squaremsquared];
+ 0x33a2 = [kmsquaredsquare];
+ 0x33a3 = [mmcubedsquare];
+ 0x33a4 = [cmcubedsquare];
+ 0x33a5 = [mcubedsquare];
+ 0x33a6 = [kmcubedsquare];
+ 0x33a7 = [moverssquare];
+ 0x33a8 = [moverssquaredsquare];
+ 0x33a9 = [pasquare];
+ 0x33aa = [kpasquare];
+ 0x33ab = [mpasquare];
+ 0x33ac = [gpasquare];
+ 0x33ad = [radsquare];
+ 0x33ae = [radoverssquare];
+ 0x33af = [radoverssquaredsquare];
+ 0x33b0 = [pssquare];
+ 0x33b1 = [nssquare];
+ 0x33b2 = [mussquare];
+ 0x33b3 = [mssquare];
+ 0x33b4 = [pvsquare];
+ 0x33b5 = [nvsquare];
+ 0x33b6 = [muvsquare];
+ 0x33b7 = [mvsquare];
+ 0x33b8 = [kvsquare];
+ 0x33b9 = [mvmegasquare];
+ 0x33ba = [pwsquare];
+ 0x33bb = [nwsquare];
+ 0x33bc = [muwsquare];
+ 0x33bd = [mwsquare];
+ 0x33be = [kwsquare];
+ 0x33bf = [mwmegasquare];
+ 0x33c0 = [kohmsquare];
+ 0x33c1 = [mohmsquare];
+ 0x33c2 = [amsquare];
+ 0x33c3 = [bqsquare];
+ 0x33c4 = [squarecc];
+ 0x33c5 = [cdsquare];
+ 0x33c6 = [coverkgsquare];
+ 0x33c7 = [cosquare];
+ 0x33c8 = [dbsquare];
+ 0x33c9 = [gysquare];
+ 0x33ca = [hasquare];
+ 0x33cb = [HPsquare];
+ 0x33cd = [KKsquare];
+ 0x33ce = [squarekmcapital];
+ 0x33cf = [ktsquare];
+ 0x33d0 = [lmsquare];
+ 0x33d1 = [squareln];
+ 0x33d2 = [squarelog];
+ 0x33d3 = [lxsquare];
+ 0x33d4 = [mbsquare];
+ 0x33d5 = [squaremil];
+ 0x33d6 = [molsquare];
+ 0x33d8 = [pmsquare];
+ 0x33db = [srsquare];
+ 0x33dc = [svsquare];
+ 0x33dd = [wbsquare];
+ 0x5344 = [twentyhangzhou];
+ 0xd801 = [emptyslot];
+ 0xd802 = [altselector];
+ 0xd803 = [Germandblssmall, SSsmall];
+ 0xd804 = [FFsmall];
+ 0xd805 = [FIsmall];
+ 0xd806 = [FLsmall];
+ 0xd807 = [FFIsmall];
+ 0xd808 = [FFLsmall];
+ 0xd809 = [capitalcompwordmark];
+ 0xd80a = [ascendercompwordmark];
+ 0xd80b = [interrobangdown];
+ 0xf6be = [dotlessj2];
+ 0xf6bf = [LL];
+ 0xf6c0 = [ll];
+ 0xf6c3 = [commaaccent];
+ 0xf6c4 = [afii10063];
+ 0xf6c5 = [afii10064];
+ 0xf6c6 = [afii10192];
+ 0xf6c7 = [afii10831];
+ 0xf6c8 = [afii10832];
+ 0xf6c9 = [Acute];
+ 0xf6ca = [Caron];
+ 0xf6cb = [Dieresis];
+ 0xf6cc = [DieresisAcute];
+ 0xf6cd = [DieresisGrave];
+ 0xf6ce = [Grave];
+ 0xf6cf = [Hungarumlaut];
+ 0xf6d0 = [Macron];
+ 0xf6d1 = [cyrBreve];
+ 0xf6d2 = [cyrFlex];
+ 0xf6d3 = [dblGrave];
+ 0xf6d4 = [cyrbreve];
+ 0xf6d5 = [cyrflex];
+ 0xf6d6 = [dblgrave];
+ 0xf6d7 = [dieresisacute];
+ 0xf6d8 = [dieresisgrave];
+ 0xf6d9 = [copyrightserif];
+ 0xf6da = [registerserif];
+ 0xf6db = [trademarkserif];
+ 0xf6dc = [onefitted];
+ 0xf6dd = [rupiah];
+ 0xf6de = [threequartersemdash, twelveudash];
+ 0xf6df = [centinferior];
+ 0xf6e0 = [centsuperior];
+ 0xf6e1 = [commainferior];
+ 0xf6e2 = [commasuperior];
+ 0xf6e3 = [dollarinferior];
+ 0xf6e4 = [dollarsuperior];
+ 0xf6e5 = [hypheninferior];
+ 0xf6e6 = [hyphensuperior];
+ 0xf6e7 = [periodinferior];
+ 0xf6e8 = [periodsuperior];
+ 0xf6e9 = [asuperior];
+ 0xf6ea = [bsuperior];
+ 0xf6eb = [dsuperior];
+ 0xf6ec = [esuperior];
+ 0xf6ed = [isuperior];
+ 0xf6ee = [lsuperior];
+ 0xf6ef = [msuperior];
+ 0xf6f0 = [osuperior];
+ 0xf6f1 = [rsuperior];
+ 0xf6f2 = [ssuperior];
+ 0xf6f3 = [tsuperior];
+ 0xf6f4 = [Brevesmall];
+ 0xf6f5 = [Caronsmall];
+ 0xf6f6 = [Circumflexsmall];
+ 0xf6f7 = [Dotaccentsmall];
+ 0xf6f8 = [Hungarumlautsmall];
+ 0xf6f9 = [Lslashsmall];
+ 0xf6fa = [OEsmall];
+ 0xf6fb = [Ogoneksmall];
+ 0xf6fc = [Ringsmall];
+ 0xf6fd = [Scaronsmall];
+ 0xf6fe = [Tildesmall];
+ 0xf6ff = [Zcaronsmall];
+ 0xf721 = [exclamsmall];
+ 0xf724 = [dollaroldstyle];
+ 0xf726 = [ampersandsmall];
+ 0xf730 = [zerooldstyle];
+ 0xf731 = [oneoldstyle];
+ 0xf732 = [twooldstyle];
+ 0xf733 = [threeoldstyle];
+ 0xf734 = [fouroldstyle];
+ 0xf735 = [fiveoldstyle];
+ 0xf736 = [sixoldstyle];
+ 0xf737 = [sevenoldstyle];
+ 0xf738 = [eightoldstyle];
+ 0xf739 = [nineoldstyle];
+ 0xf73f = [questionsmall];
+ 0xf760 = [Gravesmall];
+ 0xf761 = [Asmall];
+ 0xf762 = [Bsmall];
+ 0xf763 = [Csmall];
+ 0xf764 = [Dsmall];
+ 0xf765 = [Esmall];
+ 0xf766 = [Fsmall];
+ 0xf767 = [Gsmall];
+ 0xf768 = [Hsmall];
+ 0xf769 = [Ismall];
+ 0xf76a = [Jsmall];
+ 0xf76b = [Ksmall];
+ 0xf76c = [Lsmall];
+ 0xf76d = [Msmall];
+ 0xf76e = [Nsmall];
+ 0xf76f = [Osmall];
+ 0xf770 = [Psmall];
+ 0xf771 = [Qsmall];
+ 0xf772 = [Rsmall];
+ 0xf773 = [Ssmall];
+ 0xf774 = [Tsmall];
+ 0xf775 = [Usmall];
+ 0xf776 = [Vsmall];
+ 0xf777 = [Wsmall];
+ 0xf778 = [Xsmall];
+ 0xf779 = [Ysmall];
+ 0xf77a = [Zsmall];
+ 0xf7a1 = [exclamdownsmall];
+ 0xf7a2 = [centoldstyle];
+ 0xf7a8 = [Dieresissmall];
+ 0xf7af = [Macronsmall];
+ 0xf7b4 = [Acutesmall];
+ 0xf7b8 = [Cedillasmall];
+ 0xf7bf = [questiondownsmall];
+ 0xf7e0 = [Agravesmall];
+ 0xf7e1 = [Aacutesmall];
+ 0xf7e2 = [Acircumflexsmall];
+ 0xf7e3 = [Atildesmall];
+ 0xf7e4 = [Adieresissmall];
+ 0xf7e5 = [Aringsmall];
+ 0xf7e6 = [AEsmall];
+ 0xf7e7 = [Ccedillasmall];
+ 0xf7e8 = [Egravesmall];
+ 0xf7e9 = [Eacutesmall];
+ 0xf7ea = [Ecircumflexsmall];
+ 0xf7eb = [Edieresissmall];
+ 0xf7ec = [Igravesmall];
+ 0xf7ed = [Iacutesmall];
+ 0xf7ee = [Icircumflexsmall];
+ 0xf7ef = [Idieresissmall];
+ 0xf7f0 = [Ethsmall];
+ 0xf7f1 = [Ntildesmall];
+ 0xf7f2 = [Ogravesmall];
+ 0xf7f3 = [Oacutesmall];
+ 0xf7f4 = [Ocircumflexsmall];
+ 0xf7f5 = [Otildesmall];
+ 0xf7f6 = [Odieresissmall];
+ 0xf7f8 = [Oslashsmall];
+ 0xf7f9 = [Ugravesmall];
+ 0xf7fa = [Uacutesmall];
+ 0xf7fb = [Ucircumflexsmall];
+ 0xf7fc = [Udieresissmall];
+ 0xf7fd = [Yacutesmall];
+ 0xf7fe = [Thornsmall];
+ 0xf7ff = [Ydieresissmall];
+ 0xf884 = [maihanakatleftthai];
+ 0xf885 = [saraileftthai];
+ 0xf886 = [saraiileftthai];
+ 0xf887 = [saraueleftthai];
+ 0xf888 = [saraueeleftthai];
+ 0xf889 = [maitaikhuleftthai];
+ 0xf88a = [maiekupperleftthai];
+ 0xf88b = [maieklowrightthai];
+ 0xf88c = [maieklowleftthai];
+ 0xf88d = [maithoupperleftthai];
+ 0xf88e = [maitholowrightthai];
+ 0xf88f = [maitholowleftthai];
+ 0xf890 = [maitriupperleftthai];
+ 0xf891 = [maitrilowrightthai];
+ 0xf892 = [maitrilowleftthai];
+ 0xf893 = [maichattawaupperleftthai];
+ 0xf894 = [maichattawalowrightthai];
+ 0xf895 = [maichattawalowleftthai];
+ 0xf896 = [thanthakhatupperleftthai];
+ 0xf897 = [thanthakhatlowrightthai];
+ 0xf898 = [thanthakhatlowleftthai];
+ 0xf899 = [nikhahitleftthai];
+ 0xf8e5 = [radicalex];
+ 0xf8e6 = [arrowvertex2];
+ 0xf8e7 = [arrowhorizex];
+ 0xf8e8 = [registersans];
+ 0xf8e9 = [copyrightsans];
+ 0xf8ea = [trademarksans];
+ 0xf8eb = [parenlefttp];
+ 0xf8ec = [parenleftex2];
+ 0xf8ed = [parenleftbt];
+ 0xf8ee = [bracketlefttp];
+ 0xf8ef = [bracketleftex];
+ 0xf8f0 = [bracketleftbt];
+ 0xf8f1 = [bracelefttp];
+ 0xf8f2 = [braceleftmid2];
+ 0xf8f3 = [braceleftbt];
+ 0xf8f4 = [braceex2];
+ 0xf8f5 = [integralex];
+ 0xf8f6 = [parenrighttp];
+ 0xf8f7 = [parenrightex2];
+ 0xf8f8 = [parenrightbt];
+ 0xf8f9 = [bracketrighttp];
+ 0xf8fa = [bracketrightex];
+ 0xf8fb = [bracketrightbt];
+ 0xf8fc = [bracerighttp];
+ 0xf8fd = [bracerightmid2];
+ 0xf8fe = [bracerightbt];
+ 0xf8ff = [apple];
+ 0xfb00 = [f_f, ff];
+ 0xfb01 = [f_i, fi];
+ 0xfb02 = [f_l, fl];
+ 0xfb03 = [f_f_i, ffi];
+ 0xfb04 = [f_f_l, ffl];
+ 0xfb1f = [afii57705, doubleyodpatah, doubleyodpatahhebrew, yodyodpatahhebrew];
+ 0xfb20 = [ayinaltonehebrew];
+ 0xfb2a = [afii57694, shinshindot, shinshindothebrew];
+ 0xfb2b = [afii57695, shinsindot, shinsindothebrew];
+ 0xfb2c = [shindageshshindot, shindageshshindothebrew];
+ 0xfb2d = [shindageshsindot, shindageshsindothebrew];
+ 0xfb2e = [alefpatahhebrew];
+ 0xfb2f = [alefqamatshebrew];
+ 0xfb30 = [alefdageshhebrew];
+ 0xfb31 = [betdagesh, betdageshhebrew];
+ 0xfb32 = [gimeldagesh, gimeldageshhebrew];
+ 0xfb33 = [daletdagesh, daletdageshhebrew];
+ 0xfb34 = [hedagesh, hedageshhebrew];
+ 0xfb35 = [afii57723, vavdagesh, vavdagesh65, vavdageshhebrew];
+ 0xfb36 = [zayindagesh, zayindageshhebrew];
+ 0xfb38 = [tetdagesh, tetdageshhebrew];
+ 0xfb39 = [yoddagesh, yoddageshhebrew];
+ 0xfb3a = [finalkafdagesh, finalkafdageshhebrew];
+ 0xfb3b = [kafdagesh, kafdageshhebrew];
+ 0xfb3c = [lameddagesh, lameddageshhebrew];
+ 0xfb3e = [memdagesh, memdageshhebrew];
+ 0xfb40 = [nundagesh, nundageshhebrew];
+ 0xfb41 = [samekhdagesh, samekhdageshhebrew];
+ 0xfb43 = [pefinaldageshhebrew];
+ 0xfb44 = [pedagesh, pedageshhebrew];
+ 0xfb46 = [tsadidagesh, tsadidageshhebrew];
+ 0xfb47 = [qofdagesh, qofdageshhebrew];
+ 0xfb48 = [reshdageshhebrew];
+ 0xfb49 = [shindagesh, shindageshhebrew];
+ 0xfb4a = [tavdages, tavdagesh, tavdageshhebrew];
+ 0xfb4b = [afii57700, vavholam, vavholamhebrew];
+ 0xfb4c = [betrafehebrew];
+ 0xfb4d = [kafrafehebrew];
+ 0xfb4e = [perafehebrew];
+ 0xfb4f = [aleflamedhebrew];
+ 0xfb57 = [pehfinalarabic];
+ 0xfb58 = [pehinitialarabic];
+ 0xfb59 = [pehmedialarabic];
+ 0xfb67 = [ttehfinalarabic];
+ 0xfb68 = [ttehinitialarabic];
+ 0xfb69 = [ttehmedialarabic];
+ 0xfb6b = [vehfinalarabic];
+ 0xfb6c = [vehinitialarabic];
+ 0xfb6d = [vehmedialarabic];
+ 0xfb7b = [tchehfinalarabic];
+ 0xfb7c = [tchehinitialarabic, tchehmeeminitialarabic];
+ 0xfb7d = [tchehmedialarabic];
+ 0xfb89 = [ddalfinalarabic];
+ 0xfb8b = [jehfinalarabic];
+ 0xfb8d = [rrehfinalarabic];
+ 0xfb93 = [gaffinalarabic];
+ 0xfb94 = [gafinitialarabic];
+ 0xfb95 = [gafmedialarabic];
+ 0xfb9f = [noonghunnafinalarabic];
+ 0xfba4 = [hehhamzaaboveisolatedarabic];
+ 0xfba5 = [hehhamzaabovefinalarabic];
+ 0xfba7 = [hehfinalaltonearabic];
+ 0xfba8 = [hehinitialaltonearabic];
+ 0xfba9 = [hehmedialaltonearabic];
+ 0xfbaf = [yehbarreefinalarabic];
+ 0xfc08 = [behmeemisolatedarabic];
+ 0xfc0b = [tehjeemisolatedarabic];
+ 0xfc0c = [tehhahisolatedarabic];
+ 0xfc0e = [tehmeemisolatedarabic];
+ 0xfc48 = [meemmeemisolatedarabic];
+ 0xfc4b = [noonjeemisolatedarabic];
+ 0xfc4e = [noonmeemisolatedarabic];
+ 0xfc58 = [yehmeemisolatedarabic];
+ 0xfc5e = [shaddadammatanarabic];
+ 0xfc5f = [shaddakasratanarabic];
+ 0xfc60 = [shaddafathaarabic];
+ 0xfc61 = [shaddadammaarabic];
+ 0xfc62 = [shaddakasraarabic];
+ 0xfc6d = [behnoonfinalarabic];
+ 0xfc73 = [tehnoonfinalarabic];
+ 0xfc8d = [noonnoonfinalarabic];
+ 0xfc94 = [yehnoonfinalarabic];
+ 0xfc9f = [behmeeminitialarabic];
+ 0xfca1 = [tehjeeminitialarabic];
+ 0xfca2 = [tehhahinitialarabic];
+ 0xfca4 = [tehmeeminitialarabic];
+ 0xfcc9 = [lamjeeminitialarabic];
+ 0xfcca = [lamhahinitialarabic];
+ 0xfccb = [lamkhahinitialarabic];
+ 0xfccc = [lammeeminitialarabic];
+ 0xfcd1 = [meemmeeminitialarabic];
+ 0xfcd2 = [noonjeeminitialarabic];
+ 0xfcd5 = [noonmeeminitialarabic];
+ 0xfcdd = [yehmeeminitialarabic];
+ 0xfd3e = [parenleftaltonearabic];
+ 0xfd3f = [parenrightaltonearabic];
+ 0xfd88 = [lammeemhahinitialarabic];
+ 0xfdf2 = [lamlamhehisolatedarabic];
+ 0xfdfa = [sallallahoualayhewasallamarabic];
+ 0xfe30 = [twodotleadervertical];
+ 0xfe31 = [emdashvertical];
+ 0xfe32 = [endashvertical];
+ 0xfe33 = [underscorevertical];
+ 0xfe34 = [wavyunderscorevertical];
+ 0xfe35 = [parenleftvertical];
+ 0xfe36 = [parenrightvertical];
+ 0xfe37 = [braceleftvertical];
+ 0xfe38 = [bracerightvertical];
+ 0xfe39 = [tortoiseshellbracketleftvertical];
+ 0xfe3a = [tortoiseshellbracketrightvertical];
+ 0xfe3b = [blacklenticularbracketleftvertical];
+ 0xfe3c = [blacklenticularbracketrightvertical];
+ 0xfe3d = [dblanglebracketleftvertical];
+ 0xfe3e = [dblanglebracketrightvertical];
+ 0xfe3f = [anglebracketleftvertical];
+ 0xfe40 = [anglebracketrightvertical];
+ 0xfe41 = [cornerbracketleftvertical];
+ 0xfe42 = [cornerbracketrightvertical];
+ 0xfe43 = [whitecornerbracketleftvertical];
+ 0xfe44 = [whitecornerbracketrightvertical];
+ 0xfe49 = [overlinedashed];
+ 0xfe4a = [overlinecenterline];
+ 0xfe4b = [overlinewavy];
+ 0xfe4c = [overlinedblwavy];
+ 0xfe4d = [lowlinedashed];
+ 0xfe4e = [lowlinecenterline];
+ 0xfe4f = [underscorewavy];
+ 0xfe50 = [commasmall];
+ 0xfe52 = [periodsmall];
+ 0xfe54 = [semicolonsmall];
+ 0xfe55 = [colonsmall];
+ 0xfe59 = [parenleftsmall];
+ 0xfe5a = [parenrightsmall];
+ 0xfe5b = [braceleftsmall];
+ 0xfe5c = [bracerightsmall];
+ 0xfe5d = [tortoiseshellbracketleftsmall];
+ 0xfe5e = [tortoiseshellbracketrightsmall];
+ 0xfe5f = [numbersignsmall];
+ 0xfe61 = [asterisksmall];
+ 0xfe62 = [plussmall];
+ 0xfe63 = [hyphensmall];
+ 0xfe64 = [lesssmall];
+ 0xfe65 = [greatersmall];
+ 0xfe66 = [equalsmall];
+ 0xfe69 = [dollarsmall];
+ 0xfe6a = [percentsmall];
+ 0xfe6b = [atsmall];
+ 0xfe82 = [alefmaddaabovefinalarabic];
+ 0xfe84 = [alefhamzaabovefinalarabic];
+ 0xfe86 = [wawhamzaabovefinalarabic];
+ 0xfe88 = [alefhamzabelowfinalarabic];
+ 0xfe8a = [yehhamzaabovefinalarabic];
+ 0xfe8b = [yehhamzaaboveinitialarabic];
+ 0xfe8c = [yehhamzaabovemedialarabic];
+ 0xfe8e = [aleffinalarabic];
+ 0xfe90 = [behfinalarabic];
+ 0xfe91 = [behinitialarabic];
+ 0xfe92 = [behmedialarabic];
+ 0xfe94 = [tehmarbutafinalarabic];
+ 0xfe96 = [tehfinalarabic];
+ 0xfe97 = [tehinitialarabic];
+ 0xfe98 = [tehmedialarabic];
+ 0xfe9a = [thehfinalarabic];
+ 0xfe9b = [thehinitialarabic];
+ 0xfe9c = [thehmedialarabic];
+ 0xfe9e = [jeemfinalarabic];
+ 0xfe9f = [jeeminitialarabic];
+ 0xfea0 = [jeemmedialarabic];
+ 0xfea2 = [hahfinalarabic];
+ 0xfea3 = [hahinitialarabic];
+ 0xfea4 = [hahmedialarabic];
+ 0xfea6 = [khahfinalarabic];
+ 0xfea7 = [khahinitialarabic];
+ 0xfea8 = [khahmedialarabic];
+ 0xfeaa = [dalfinalarabic];
+ 0xfeac = [thalfinalarabic];
+ 0xfeae = [rehfinalarabic];
+ 0xfeb0 = [zainfinalarabic];
+ 0xfeb2 = [seenfinalarabic];
+ 0xfeb3 = [seeninitialarabic];
+ 0xfeb4 = [seenmedialarabic];
+ 0xfeb6 = [sheenfinalarabic];
+ 0xfeb7 = [sheeninitialarabic];
+ 0xfeb8 = [sheenmedialarabic];
+ 0xfeba = [sadfinalarabic];
+ 0xfebb = [sadinitialarabic];
+ 0xfebc = [sadmedialarabic];
+ 0xfebe = [dadfinalarabic];
+ 0xfebf = [dadinitialarabic];
+ 0xfec0 = [dadmedialarabic];
+ 0xfec2 = [tahfinalarabic];
+ 0xfec3 = [tahinitialarabic];
+ 0xfec4 = [tahmedialarabic];
+ 0xfec6 = [zahfinalarabic];
+ 0xfec7 = [zahinitialarabic];
+ 0xfec8 = [zahmedialarabic];
+ 0xfeca = [ainfinalarabic];
+ 0xfecb = [aininitialarabic];
+ 0xfecc = [ainmedialarabic];
+ 0xfece = [ghainfinalarabic];
+ 0xfecf = [ghaininitialarabic];
+ 0xfed0 = [ghainmedialarabic];
+ 0xfed2 = [fehfinalarabic];
+ 0xfed3 = [fehinitialarabic];
+ 0xfed4 = [fehmedialarabic];
+ 0xfed6 = [qaffinalarabic];
+ 0xfed7 = [qafinitialarabic];
+ 0xfed8 = [qafmedialarabic];
+ 0xfeda = [kaffinalarabic];
+ 0xfedb = [kafinitialarabic];
+ 0xfedc = [kafmedialarabic];
+ 0xfede = [lamfinalarabic];
+ 0xfedf = [laminitialarabic, lammeemjeeminitialarabic, lammeemkhahinitialarabic];
+ 0xfee0 = [lammedialarabic];
+ 0xfee2 = [meemfinalarabic];
+ 0xfee3 = [meeminitialarabic];
+ 0xfee4 = [meemmedialarabic];
+ 0xfee6 = [noonfinalarabic];
+ 0xfee7 = [noonhehinitialarabic, nooninitialarabic];
+ 0xfee8 = [noonmedialarabic];
+ 0xfeea = [hehfinalalttwoarabic, hehfinalarabic];
+ 0xfeeb = [hehinitialarabic];
+ 0xfeec = [hehmedialarabic];
+ 0xfeee = [wawfinalarabic];
+ 0xfef0 = [alefmaksurafinalarabic];
+ 0xfef2 = [yehfinalarabic];
+ 0xfef3 = [alefmaksurainitialarabic, yehinitialarabic];
+ 0xfef4 = [alefmaksuramedialarabic, yehmedialarabic];
+ 0xfef5 = [lamalefmaddaaboveisolatedarabic];
+ 0xfef6 = [lamalefmaddaabovefinalarabic];
+ 0xfef7 = [lamalefhamzaaboveisolatedarabic];
+ 0xfef8 = [lamalefhamzaabovefinalarabic];
+ 0xfef9 = [lamalefhamzabelowisolatedarabic];
+ 0xfefa = [lamalefhamzabelowfinalarabic];
+ 0xfefb = [lamalefisolatedarabic];
+ 0xfefc = [lamaleffinalarabic];
+ 0xfeff = [zerowidthjoiner];
+ 0xff01 = [exclammonospace];
+ 0xff02 = [quotedblmonospace];
+ 0xff03 = [numbersignmonospace];
+ 0xff04 = [dollarmonospace];
+ 0xff05 = [percentmonospace];
+ 0xff06 = [ampersandmonospace];
+ 0xff07 = [quotesinglemonospace];
+ 0xff08 = [parenleftmonospace];
+ 0xff09 = [parenrightmonospace];
+ 0xff0a = [asteriskmonospace];
+ 0xff0b = [plusmonospace];
+ 0xff0c = [commamonospace];
+ 0xff0d = [hyphenmonospace];
+ 0xff0e = [periodmonospace];
+ 0xff0f = [slashmonospace];
+ 0xff10 = [zeromonospace];
+ 0xff11 = [onemonospace];
+ 0xff12 = [twomonospace];
+ 0xff13 = [threemonospace];
+ 0xff14 = [fourmonospace];
+ 0xff15 = [fivemonospace];
+ 0xff16 = [sixmonospace];
+ 0xff17 = [sevenmonospace];
+ 0xff18 = [eightmonospace];
+ 0xff19 = [ninemonospace];
+ 0xff1a = [colonmonospace];
+ 0xff1b = [semicolonmonospace];
+ 0xff1c = [lessmonospace];
+ 0xff1d = [equalmonospace];
+ 0xff1e = [greatermonospace];
+ 0xff1f = [questionmonospace];
+ 0xff20 = [atmonospace];
+ 0xff21 = [Amonospace];
+ 0xff22 = [Bmonospace];
+ 0xff23 = [Cmonospace];
+ 0xff24 = [Dmonospace];
+ 0xff25 = [Emonospace];
+ 0xff26 = [Fmonospace];
+ 0xff27 = [Gmonospace];
+ 0xff28 = [Hmonospace];
+ 0xff29 = [Imonospace];
+ 0xff2a = [Jmonospace];
+ 0xff2b = [Kmonospace];
+ 0xff2c = [Lmonospace];
+ 0xff2d = [Mmonospace];
+ 0xff2e = [Nmonospace];
+ 0xff2f = [Omonospace];
+ 0xff30 = [Pmonospace];
+ 0xff31 = [Qmonospace];
+ 0xff32 = [Rmonospace];
+ 0xff33 = [Smonospace];
+ 0xff34 = [Tmonospace];
+ 0xff35 = [Umonospace];
+ 0xff36 = [Vmonospace];
+ 0xff37 = [Wmonospace];
+ 0xff38 = [Xmonospace];
+ 0xff39 = [Ymonospace];
+ 0xff3a = [Zmonospace];
+ 0xff3b = [bracketleftmonospace];
+ 0xff3c = [backslashmonospace];
+ 0xff3d = [bracketrightmonospace];
+ 0xff3e = [asciicircummonospace];
+ 0xff3f = [underscoremonospace];
+ 0xff40 = [gravemonospace];
+ 0xff41 = [amonospace];
+ 0xff42 = [bmonospace];
+ 0xff43 = [cmonospace];
+ 0xff44 = [dmonospace];
+ 0xff45 = [emonospace];
+ 0xff46 = [fmonospace];
+ 0xff47 = [gmonospace];
+ 0xff48 = [hmonospace];
+ 0xff49 = [imonospace];
+ 0xff4a = [jmonospace];
+ 0xff4b = [kmonospace];
+ 0xff4c = [lmonospace];
+ 0xff4d = [mmonospace];
+ 0xff4e = [nmonospace];
+ 0xff4f = [omonospace];
+ 0xff50 = [pmonospace];
+ 0xff51 = [qmonospace];
+ 0xff52 = [rmonospace];
+ 0xff53 = [smonospace];
+ 0xff54 = [tmonospace];
+ 0xff55 = [umonospace];
+ 0xff56 = [vmonospace];
+ 0xff57 = [wmonospace];
+ 0xff58 = [xmonospace];
+ 0xff59 = [ymonospace];
+ 0xff5a = [zmonospace];
+ 0xff5b = [braceleftmonospace];
+ 0xff5c = [barmonospace];
+ 0xff5d = [bracerightmonospace];
+ 0xff5e = [asciitildemonospace];
+ 0xff61 = [periodhalfwidth];
+ 0xff62 = [cornerbracketlefthalfwidth];
+ 0xff63 = [cornerbracketrighthalfwidth];
+ 0xff64 = [ideographiccommaleft];
+ 0xff65 = [middledotkatakanahalfwidth];
+ 0xff66 = [wokatakanahalfwidth];
+ 0xff67 = [asmallkatakanahalfwidth];
+ 0xff68 = [ismallkatakanahalfwidth];
+ 0xff69 = [usmallkatakanahalfwidth];
+ 0xff6a = [esmallkatakanahalfwidth];
+ 0xff6b = [osmallkatakanahalfwidth];
+ 0xff6c = [yasmallkatakanahalfwidth];
+ 0xff6d = [yusmallkatakanahalfwidth];
+ 0xff6e = [yosmallkatakanahalfwidth];
+ 0xff6f = [tusmallkatakanahalfwidth];
+ 0xff70 = [katahiraprolongmarkhalfwidth];
+ 0xff71 = [akatakanahalfwidth];
+ 0xff72 = [ikatakanahalfwidth];
+ 0xff73 = [ukatakanahalfwidth];
+ 0xff74 = [ekatakanahalfwidth];
+ 0xff75 = [okatakanahalfwidth];
+ 0xff76 = [kakatakanahalfwidth];
+ 0xff77 = [kikatakanahalfwidth];
+ 0xff78 = [kukatakanahalfwidth];
+ 0xff79 = [kekatakanahalfwidth];
+ 0xff7a = [kokatakanahalfwidth];
+ 0xff7b = [sakatakanahalfwidth];
+ 0xff7c = [sikatakanahalfwidth];
+ 0xff7d = [sukatakanahalfwidth];
+ 0xff7e = [sekatakanahalfwidth];
+ 0xff7f = [sokatakanahalfwidth];
+ 0xff80 = [takatakanahalfwidth];
+ 0xff81 = [tikatakanahalfwidth];
+ 0xff82 = [tukatakanahalfwidth];
+ 0xff83 = [tekatakanahalfwidth];
+ 0xff84 = [tokatakanahalfwidth];
+ 0xff85 = [nakatakanahalfwidth];
+ 0xff86 = [nikatakanahalfwidth];
+ 0xff87 = [nukatakanahalfwidth];
+ 0xff88 = [nekatakanahalfwidth];
+ 0xff89 = [nokatakanahalfwidth];
+ 0xff8a = [hakatakanahalfwidth];
+ 0xff8b = [hikatakanahalfwidth];
+ 0xff8c = [hukatakanahalfwidth];
+ 0xff8d = [hekatakanahalfwidth];
+ 0xff8e = [hokatakanahalfwidth];
+ 0xff8f = [makatakanahalfwidth];
+ 0xff90 = [mikatakanahalfwidth];
+ 0xff91 = [mukatakanahalfwidth];
+ 0xff92 = [mekatakanahalfwidth];
+ 0xff93 = [mokatakanahalfwidth];
+ 0xff94 = [yakatakanahalfwidth];
+ 0xff95 = [yukatakanahalfwidth];
+ 0xff96 = [yokatakanahalfwidth];
+ 0xff97 = [rakatakanahalfwidth];
+ 0xff98 = [rikatakanahalfwidth];
+ 0xff99 = [rukatakanahalfwidth];
+ 0xff9a = [rekatakanahalfwidth];
+ 0xff9b = [rokatakanahalfwidth];
+ 0xff9c = [wakatakanahalfwidth];
+ 0xff9d = [nkatakanahalfwidth];
+ 0xff9e = [voicedmarkkanahalfwidth];
+ 0xff9f = [semivoicedmarkkanahalfwidth];
+ 0xffe0 = [centmonospace];
+ 0xffe1 = [sterlingmonospace];
+ 0xffe3 = [macronmonospace];
+ 0xffe5 = [yenmonospace];
+ 0xffe6 = [wonmonospace];
+}
diff --git a/vendor/lopdf/src/encodings/mappings.rs b/vendor/lopdf/src/encodings/mappings.rs
new file mode 100644
index 000000000..a49fff83c
--- /dev/null
+++ b/vendor/lopdf/src/encodings/mappings.rs
@@ -0,0 +1,1820 @@
+use super::glyphnames::Glyph;
+
+pub type CodedCharacterSet = [Option<Glyph>; 256];
+pub const MAC_ROMAN_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclam),
+ Some(Glyph::quotedbl),
+ Some(Glyph::numbersign),
+ Some(Glyph::dollar),
+ Some(Glyph::percent),
+ Some(Glyph::ampersand),
+ Some(Glyph::quotesingle),
+ Some(Glyph::parenleft),
+ Some(Glyph::parenright),
+ Some(Glyph::asterisk),
+ Some(Glyph::plus),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::slash),
+ Some(Glyph::zero),
+ Some(Glyph::one),
+ Some(Glyph::two),
+ Some(Glyph::three),
+ Some(Glyph::four),
+ Some(Glyph::five),
+ Some(Glyph::six),
+ Some(Glyph::seven),
+ Some(Glyph::eight),
+ Some(Glyph::nine),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::less),
+ Some(Glyph::equal),
+ Some(Glyph::greater),
+ Some(Glyph::question),
+ Some(Glyph::at),
+ Some(Glyph::A),
+ Some(Glyph::B),
+ Some(Glyph::C),
+ Some(Glyph::D),
+ Some(Glyph::E),
+ Some(Glyph::F),
+ Some(Glyph::G),
+ Some(Glyph::H),
+ Some(Glyph::I),
+ Some(Glyph::J),
+ Some(Glyph::K),
+ Some(Glyph::L),
+ Some(Glyph::M),
+ Some(Glyph::N),
+ Some(Glyph::O),
+ Some(Glyph::P),
+ Some(Glyph::Q),
+ Some(Glyph::R),
+ Some(Glyph::S),
+ Some(Glyph::T),
+ Some(Glyph::U),
+ Some(Glyph::V),
+ Some(Glyph::W),
+ Some(Glyph::X),
+ Some(Glyph::Y),
+ Some(Glyph::Z),
+ Some(Glyph::bracketleft),
+ Some(Glyph::backslash),
+ Some(Glyph::bracketright),
+ Some(Glyph::asciicircum),
+ Some(Glyph::underscore),
+ Some(Glyph::grave),
+ Some(Glyph::a),
+ Some(Glyph::b),
+ Some(Glyph::c),
+ Some(Glyph::d),
+ Some(Glyph::e),
+ Some(Glyph::f),
+ Some(Glyph::g),
+ Some(Glyph::h),
+ Some(Glyph::i),
+ Some(Glyph::j),
+ Some(Glyph::k),
+ Some(Glyph::l),
+ Some(Glyph::m),
+ Some(Glyph::n),
+ Some(Glyph::o),
+ Some(Glyph::p),
+ Some(Glyph::q),
+ Some(Glyph::r),
+ Some(Glyph::s),
+ Some(Glyph::t),
+ Some(Glyph::u),
+ Some(Glyph::v),
+ Some(Glyph::w),
+ Some(Glyph::x),
+ Some(Glyph::y),
+ Some(Glyph::z),
+ Some(Glyph::braceleft),
+ Some(Glyph::bar),
+ Some(Glyph::braceright),
+ Some(Glyph::asciitilde),
+ None,
+ Some(Glyph::Adieresis),
+ Some(Glyph::Aring),
+ Some(Glyph::Ccedilla),
+ Some(Glyph::Eacute),
+ Some(Glyph::Ntilde),
+ Some(Glyph::Odieresis),
+ Some(Glyph::Udieresis),
+ Some(Glyph::aacute),
+ Some(Glyph::agrave),
+ Some(Glyph::acircumflex),
+ Some(Glyph::adieresis),
+ Some(Glyph::atilde),
+ Some(Glyph::aring),
+ Some(Glyph::ccedilla),
+ Some(Glyph::eacute),
+ Some(Glyph::egrave),
+ Some(Glyph::ecircumflex),
+ Some(Glyph::edieresis),
+ Some(Glyph::iacute),
+ Some(Glyph::igrave),
+ Some(Glyph::icircumflex),
+ Some(Glyph::idieresis),
+ Some(Glyph::ntilde),
+ Some(Glyph::oacute),
+ Some(Glyph::ograve),
+ Some(Glyph::ocircumflex),
+ Some(Glyph::odieresis),
+ Some(Glyph::otilde),
+ Some(Glyph::uacute),
+ Some(Glyph::ugrave),
+ Some(Glyph::ucircumflex),
+ Some(Glyph::udieresis),
+ Some(Glyph::dagger),
+ Some(Glyph::degree),
+ Some(Glyph::cent),
+ Some(Glyph::sterling),
+ Some(Glyph::section),
+ Some(Glyph::bullet),
+ Some(Glyph::paragraph),
+ Some(Glyph::germandbls),
+ Some(Glyph::registered),
+ Some(Glyph::copyright),
+ Some(Glyph::trademark),
+ Some(Glyph::acute),
+ Some(Glyph::dieresis),
+ Some(Glyph::notequal),
+ Some(Glyph::AE),
+ Some(Glyph::Oslash),
+ Some(Glyph::infinity),
+ Some(Glyph::plusminus),
+ Some(Glyph::lessequal),
+ Some(Glyph::greaterequal),
+ Some(Glyph::yen),
+ Some(Glyph::mu),
+ Some(Glyph::partialdiff),
+ Some(Glyph::summation),
+ Some(Glyph::product),
+ Some(Glyph::pi),
+ Some(Glyph::integral),
+ Some(Glyph::ordfeminine),
+ Some(Glyph::ordmasculine),
+ Some(Glyph::Omega),
+ Some(Glyph::ae),
+ Some(Glyph::oslash),
+ Some(Glyph::questiondown),
+ Some(Glyph::exclamdown),
+ Some(Glyph::logicalnot),
+ Some(Glyph::radical),
+ Some(Glyph::florin),
+ Some(Glyph::approxequal),
+ Some(Glyph::Delta),
+ Some(Glyph::guillemotleft),
+ Some(Glyph::guillemotright),
+ Some(Glyph::ellipsis),
+ Some(Glyph::space),
+ Some(Glyph::Agrave),
+ Some(Glyph::Atilde),
+ Some(Glyph::Otilde),
+ Some(Glyph::OE),
+ Some(Glyph::oe),
+ Some(Glyph::endash),
+ Some(Glyph::emdash),
+ Some(Glyph::quotedblleft),
+ Some(Glyph::quotedblright),
+ Some(Glyph::quoteleft),
+ Some(Glyph::quoteright),
+ Some(Glyph::divide),
+ Some(Glyph::lozenge),
+ Some(Glyph::ydieresis),
+ Some(Glyph::Ydieresis),
+ Some(Glyph::fraction),
+ Some(Glyph::currency),
+ Some(Glyph::guilsinglleft),
+ Some(Glyph::guilsinglright),
+ Some(Glyph::fi),
+ Some(Glyph::fl),
+ Some(Glyph::daggerdbl),
+ Some(Glyph::periodcentered),
+ Some(Glyph::quotesinglbase),
+ Some(Glyph::quotedblbase),
+ Some(Glyph::perthousand),
+ Some(Glyph::Acircumflex),
+ Some(Glyph::Ecircumflex),
+ Some(Glyph::Aacute),
+ Some(Glyph::Edieresis),
+ Some(Glyph::Egrave),
+ Some(Glyph::Iacute),
+ Some(Glyph::Icircumflex),
+ Some(Glyph::Idieresis),
+ Some(Glyph::Igrave),
+ Some(Glyph::Oacute),
+ Some(Glyph::Ocircumflex),
+ Some(Glyph::apple),
+ Some(Glyph::Ograve),
+ Some(Glyph::Uacute),
+ Some(Glyph::Ucircumflex),
+ Some(Glyph::Ugrave),
+ Some(Glyph::dotlessi),
+ Some(Glyph::circumflex),
+ Some(Glyph::tilde),
+ Some(Glyph::macron),
+ Some(Glyph::breve),
+ Some(Glyph::dotaccent),
+ Some(Glyph::ring),
+ Some(Glyph::cedilla),
+ Some(Glyph::hungarumlaut),
+ Some(Glyph::ogonek),
+ Some(Glyph::caron),
+];
+
+pub const MAC_EXPERT_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclamsmall),
+ Some(Glyph::Hungarumlautsmall),
+ Some(Glyph::centoldstyle),
+ Some(Glyph::dollaroldstyle),
+ Some(Glyph::dollarsuperior),
+ Some(Glyph::ampersandsmall),
+ Some(Glyph::Acutesmall),
+ Some(Glyph::parenleftsuperior),
+ Some(Glyph::parenrightsuperior),
+ Some(Glyph::twodotenleader),
+ Some(Glyph::onedotenleader),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::fraction),
+ Some(Glyph::zerooldstyle),
+ Some(Glyph::oneoldstyle),
+ Some(Glyph::twooldstyle),
+ Some(Glyph::threeoldstyle),
+ Some(Glyph::fouroldstyle),
+ Some(Glyph::fiveoldstyle),
+ Some(Glyph::sixoldstyle),
+ Some(Glyph::sevenoldstyle),
+ Some(Glyph::eightoldstyle),
+ Some(Glyph::nineoldstyle),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ None,
+ Some(Glyph::threequartersemdash),
+ None,
+ Some(Glyph::questionsmall),
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::Ethsmall),
+ None,
+ None,
+ Some(Glyph::onequarter),
+ Some(Glyph::onehalf),
+ Some(Glyph::threequarters),
+ Some(Glyph::oneeighth),
+ Some(Glyph::threeeighths),
+ Some(Glyph::fiveeighths),
+ Some(Glyph::seveneighths),
+ Some(Glyph::onethird),
+ Some(Glyph::twothirds),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::ff),
+ Some(Glyph::fi),
+ Some(Glyph::fl),
+ Some(Glyph::ffi),
+ Some(Glyph::ffl),
+ Some(Glyph::parenleftinferior),
+ None,
+ Some(Glyph::parenrightinferior),
+ Some(Glyph::Circumflexsmall),
+ Some(Glyph::hypheninferior),
+ Some(Glyph::Gravesmall),
+ Some(Glyph::Asmall),
+ Some(Glyph::Bsmall),
+ Some(Glyph::Csmall),
+ Some(Glyph::Dsmall),
+ Some(Glyph::Esmall),
+ Some(Glyph::Fsmall),
+ Some(Glyph::Gsmall),
+ Some(Glyph::Hsmall),
+ Some(Glyph::Ismall),
+ Some(Glyph::Jsmall),
+ Some(Glyph::Ksmall),
+ Some(Glyph::Lsmall),
+ Some(Glyph::Msmall),
+ Some(Glyph::Nsmall),
+ Some(Glyph::Osmall),
+ Some(Glyph::Psmall),
+ Some(Glyph::Qsmall),
+ Some(Glyph::Rsmall),
+ Some(Glyph::Ssmall),
+ Some(Glyph::Tsmall),
+ Some(Glyph::Usmall),
+ Some(Glyph::Vsmall),
+ Some(Glyph::Wsmall),
+ Some(Glyph::Xsmall),
+ Some(Glyph::Ysmall),
+ Some(Glyph::Zsmall),
+ Some(Glyph::colonmonetary),
+ Some(Glyph::onefitted),
+ Some(Glyph::rupiah),
+ Some(Glyph::Tildesmall),
+ None,
+ None,
+ Some(Glyph::asuperior),
+ Some(Glyph::centsuperior),
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::Aacutesmall),
+ Some(Glyph::Agravesmall),
+ Some(Glyph::Acircumflexsmall),
+ Some(Glyph::Adieresissmall),
+ Some(Glyph::Atildesmall),
+ Some(Glyph::Aringsmall),
+ Some(Glyph::Ccedillasmall),
+ Some(Glyph::Eacutesmall),
+ Some(Glyph::Egravesmall),
+ Some(Glyph::Ecircumflexsmall),
+ Some(Glyph::Edieresissmall),
+ Some(Glyph::Iacutesmall),
+ Some(Glyph::Igravesmall),
+ Some(Glyph::Icircumflexsmall),
+ Some(Glyph::Idieresissmall),
+ Some(Glyph::Ntildesmall),
+ Some(Glyph::Oacutesmall),
+ Some(Glyph::Ogravesmall),
+ Some(Glyph::Ocircumflexsmall),
+ Some(Glyph::Odieresissmall),
+ Some(Glyph::Otildesmall),
+ Some(Glyph::Uacutesmall),
+ Some(Glyph::Ugravesmall),
+ Some(Glyph::Ucircumflexsmall),
+ Some(Glyph::Udieresissmall),
+ None,
+ Some(Glyph::eightsuperior),
+ Some(Glyph::fourinferior),
+ Some(Glyph::threeinferior),
+ Some(Glyph::sixinferior),
+ Some(Glyph::eightinferior),
+ Some(Glyph::seveninferior),
+ Some(Glyph::Scaronsmall),
+ None,
+ Some(Glyph::centinferior),
+ Some(Glyph::twoinferior),
+ None,
+ Some(Glyph::Dieresissmall),
+ None,
+ Some(Glyph::Caronsmall),
+ Some(Glyph::osuperior),
+ Some(Glyph::fiveinferior),
+ None,
+ Some(Glyph::commainferior),
+ Some(Glyph::periodinferior),
+ Some(Glyph::Yacutesmall),
+ None,
+ Some(Glyph::dollarinferior),
+ None,
+ None,
+ Some(Glyph::Thornsmall),
+ None,
+ Some(Glyph::nineinferior),
+ Some(Glyph::zeroinferior),
+ Some(Glyph::Zcaronsmall),
+ Some(Glyph::AEsmall),
+ Some(Glyph::Oslashsmall),
+ Some(Glyph::questiondownsmall),
+ Some(Glyph::oneinferior),
+ Some(Glyph::Lslashsmall),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::Cedillasmall),
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::OEsmall),
+ Some(Glyph::figuredash),
+ Some(Glyph::hyphensuperior),
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::exclamdownsmall),
+ None,
+ Some(Glyph::Ydieresissmall),
+ None,
+ Some(Glyph::onesuperior),
+ Some(Glyph::twosuperior),
+ Some(Glyph::threesuperior),
+ Some(Glyph::foursuperior),
+ Some(Glyph::fivesuperior),
+ Some(Glyph::sixsuperior),
+ Some(Glyph::sevensuperior),
+ Some(Glyph::ninesuperior),
+ Some(Glyph::zerosuperior),
+ None,
+ Some(Glyph::esuperior),
+ Some(Glyph::rsuperior),
+ Some(Glyph::tsuperior),
+ None,
+ None,
+ Some(Glyph::isuperior),
+ Some(Glyph::ssuperior),
+ Some(Glyph::dsuperior),
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::lsuperior),
+ Some(Glyph::Ogoneksmall),
+ Some(Glyph::Brevesmall),
+ Some(Glyph::Macronsmall),
+ Some(Glyph::bsuperior),
+ Some(Glyph::nsuperior),
+ Some(Glyph::msuperior),
+ Some(Glyph::commasuperior),
+ Some(Glyph::periodsuperior),
+ Some(Glyph::Dotaccentsmall),
+ Some(Glyph::Ringsmall),
+ None,
+ None,
+ None,
+ None,
+];
+
+pub const WIN_ANSI_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclam),
+ Some(Glyph::quotedbl),
+ Some(Glyph::numbersign),
+ Some(Glyph::dollar),
+ Some(Glyph::percent),
+ Some(Glyph::ampersand),
+ Some(Glyph::quotesingle),
+ Some(Glyph::parenleft),
+ Some(Glyph::parenright),
+ Some(Glyph::asterisk),
+ Some(Glyph::plus),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::slash),
+ Some(Glyph::zero),
+ Some(Glyph::one),
+ Some(Glyph::two),
+ Some(Glyph::three),
+ Some(Glyph::four),
+ Some(Glyph::five),
+ Some(Glyph::six),
+ Some(Glyph::seven),
+ Some(Glyph::eight),
+ Some(Glyph::nine),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::less),
+ Some(Glyph::equal),
+ Some(Glyph::greater),
+ Some(Glyph::question),
+ Some(Glyph::at),
+ Some(Glyph::A),
+ Some(Glyph::B),
+ Some(Glyph::C),
+ Some(Glyph::D),
+ Some(Glyph::E),
+ Some(Glyph::F),
+ Some(Glyph::G),
+ Some(Glyph::H),
+ Some(Glyph::I),
+ Some(Glyph::J),
+ Some(Glyph::K),
+ Some(Glyph::L),
+ Some(Glyph::M),
+ Some(Glyph::N),
+ Some(Glyph::O),
+ Some(Glyph::P),
+ Some(Glyph::Q),
+ Some(Glyph::R),
+ Some(Glyph::S),
+ Some(Glyph::T),
+ Some(Glyph::U),
+ Some(Glyph::V),
+ Some(Glyph::W),
+ Some(Glyph::X),
+ Some(Glyph::Y),
+ Some(Glyph::Z),
+ Some(Glyph::bracketleft),
+ Some(Glyph::backslash),
+ Some(Glyph::bracketright),
+ Some(Glyph::asciicircum),
+ Some(Glyph::underscore),
+ Some(Glyph::grave),
+ Some(Glyph::a),
+ Some(Glyph::b),
+ Some(Glyph::c),
+ Some(Glyph::d),
+ Some(Glyph::e),
+ Some(Glyph::f),
+ Some(Glyph::g),
+ Some(Glyph::h),
+ Some(Glyph::i),
+ Some(Glyph::j),
+ Some(Glyph::k),
+ Some(Glyph::l),
+ Some(Glyph::m),
+ Some(Glyph::n),
+ Some(Glyph::o),
+ Some(Glyph::p),
+ Some(Glyph::q),
+ Some(Glyph::r),
+ Some(Glyph::s),
+ Some(Glyph::t),
+ Some(Glyph::u),
+ Some(Glyph::v),
+ Some(Glyph::w),
+ Some(Glyph::x),
+ Some(Glyph::y),
+ Some(Glyph::z),
+ Some(Glyph::braceleft),
+ Some(Glyph::bar),
+ Some(Glyph::braceright),
+ Some(Glyph::asciitilde),
+ Some(Glyph::bullet),
+ Some(Glyph::Euro),
+ Some(Glyph::bullet),
+ Some(Glyph::quotesinglbase),
+ Some(Glyph::florin),
+ Some(Glyph::quotedblbase),
+ Some(Glyph::ellipsis),
+ Some(Glyph::dagger),
+ Some(Glyph::daggerdbl),
+ Some(Glyph::circumflex),
+ Some(Glyph::perthousand),
+ Some(Glyph::Scaron),
+ Some(Glyph::guilsinglleft),
+ Some(Glyph::OE),
+ Some(Glyph::bullet),
+ Some(Glyph::Zcaron),
+ Some(Glyph::bullet),
+ Some(Glyph::bullet),
+ Some(Glyph::quoteleft),
+ Some(Glyph::quoteright),
+ Some(Glyph::quotedblleft),
+ Some(Glyph::quotedblright),
+ Some(Glyph::bullet),
+ Some(Glyph::endash),
+ Some(Glyph::emdash),
+ Some(Glyph::tilde),
+ Some(Glyph::trademark),
+ Some(Glyph::scaron),
+ Some(Glyph::guilsinglright),
+ Some(Glyph::oe),
+ Some(Glyph::bullet),
+ Some(Glyph::zcaron),
+ Some(Glyph::Ydieresis),
+ Some(Glyph::space),
+ Some(Glyph::exclamdown),
+ Some(Glyph::cent),
+ Some(Glyph::sterling),
+ Some(Glyph::currency),
+ Some(Glyph::yen),
+ Some(Glyph::brokenbar),
+ Some(Glyph::section),
+ Some(Glyph::dieresis),
+ Some(Glyph::copyright),
+ Some(Glyph::ordfeminine),
+ Some(Glyph::guillemotleft),
+ Some(Glyph::logicalnot),
+ Some(Glyph::hyphen),
+ Some(Glyph::registered),
+ Some(Glyph::macron),
+ Some(Glyph::degree),
+ Some(Glyph::plusminus),
+ Some(Glyph::twosuperior),
+ Some(Glyph::threesuperior),
+ Some(Glyph::acute),
+ Some(Glyph::mu),
+ Some(Glyph::paragraph),
+ Some(Glyph::periodcentered),
+ Some(Glyph::cedilla),
+ Some(Glyph::onesuperior),
+ Some(Glyph::ordmasculine),
+ Some(Glyph::guillemotright),
+ Some(Glyph::onequarter),
+ Some(Glyph::onehalf),
+ Some(Glyph::threequarters),
+ Some(Glyph::questiondown),
+ Some(Glyph::Agrave),
+ Some(Glyph::Aacute),
+ Some(Glyph::Acircumflex),
+ Some(Glyph::Atilde),
+ Some(Glyph::Adieresis),
+ Some(Glyph::Aring),
+ Some(Glyph::AE),
+ Some(Glyph::Ccedilla),
+ Some(Glyph::Egrave),
+ Some(Glyph::Eacute),
+ Some(Glyph::Ecircumflex),
+ Some(Glyph::Edieresis),
+ Some(Glyph::Igrave),
+ Some(Glyph::Iacute),
+ Some(Glyph::Icircumflex),
+ Some(Glyph::Idieresis),
+ Some(Glyph::Eth),
+ Some(Glyph::Ntilde),
+ Some(Glyph::Ograve),
+ Some(Glyph::Oacute),
+ Some(Glyph::Ocircumflex),
+ Some(Glyph::Otilde),
+ Some(Glyph::Odieresis),
+ Some(Glyph::multiply),
+ Some(Glyph::Oslash),
+ Some(Glyph::Ugrave),
+ Some(Glyph::Uacute),
+ Some(Glyph::Ucircumflex),
+ Some(Glyph::Udieresis),
+ Some(Glyph::Yacute),
+ Some(Glyph::Thorn),
+ Some(Glyph::germandbls),
+ Some(Glyph::agrave),
+ Some(Glyph::aacute),
+ Some(Glyph::acircumflex),
+ Some(Glyph::atilde),
+ Some(Glyph::adieresis),
+ Some(Glyph::aring),
+ Some(Glyph::ae),
+ Some(Glyph::ccedilla),
+ Some(Glyph::egrave),
+ Some(Glyph::eacute),
+ Some(Glyph::ecircumflex),
+ Some(Glyph::edieresis),
+ Some(Glyph::igrave),
+ Some(Glyph::iacute),
+ Some(Glyph::icircumflex),
+ Some(Glyph::idieresis),
+ Some(Glyph::eth),
+ Some(Glyph::ntilde),
+ Some(Glyph::ograve),
+ Some(Glyph::oacute),
+ Some(Glyph::ocircumflex),
+ Some(Glyph::otilde),
+ Some(Glyph::odieresis),
+ Some(Glyph::divide),
+ Some(Glyph::oslash),
+ Some(Glyph::ugrave),
+ Some(Glyph::uacute),
+ Some(Glyph::ucircumflex),
+ Some(Glyph::udieresis),
+ Some(Glyph::yacute),
+ Some(Glyph::thorn),
+ Some(Glyph::ydieresis),
+];
+
+pub const STANDARD_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclam),
+ Some(Glyph::quotedbl),
+ Some(Glyph::numbersign),
+ Some(Glyph::dollar),
+ Some(Glyph::percent),
+ Some(Glyph::ampersand),
+ Some(Glyph::quoteright),
+ Some(Glyph::parenleft),
+ Some(Glyph::parenright),
+ Some(Glyph::asterisk),
+ Some(Glyph::plus),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::slash),
+ Some(Glyph::zero),
+ Some(Glyph::one),
+ Some(Glyph::two),
+ Some(Glyph::three),
+ Some(Glyph::four),
+ Some(Glyph::five),
+ Some(Glyph::six),
+ Some(Glyph::seven),
+ Some(Glyph::eight),
+ Some(Glyph::nine),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::less),
+ Some(Glyph::equal),
+ Some(Glyph::greater),
+ Some(Glyph::question),
+ Some(Glyph::at),
+ Some(Glyph::A),
+ Some(Glyph::B),
+ Some(Glyph::C),
+ Some(Glyph::D),
+ Some(Glyph::E),
+ Some(Glyph::F),
+ Some(Glyph::G),
+ Some(Glyph::H),
+ Some(Glyph::I),
+ Some(Glyph::J),
+ Some(Glyph::K),
+ Some(Glyph::L),
+ Some(Glyph::M),
+ Some(Glyph::N),
+ Some(Glyph::O),
+ Some(Glyph::P),
+ Some(Glyph::Q),
+ Some(Glyph::R),
+ Some(Glyph::S),
+ Some(Glyph::T),
+ Some(Glyph::U),
+ Some(Glyph::V),
+ Some(Glyph::W),
+ Some(Glyph::X),
+ Some(Glyph::Y),
+ Some(Glyph::Z),
+ Some(Glyph::bracketleft),
+ Some(Glyph::backslash),
+ Some(Glyph::bracketright),
+ Some(Glyph::asciicircum),
+ Some(Glyph::underscore),
+ Some(Glyph::quoteleft),
+ Some(Glyph::a),
+ Some(Glyph::b),
+ Some(Glyph::c),
+ Some(Glyph::d),
+ Some(Glyph::e),
+ Some(Glyph::f),
+ Some(Glyph::g),
+ Some(Glyph::h),
+ Some(Glyph::i),
+ Some(Glyph::j),
+ Some(Glyph::k),
+ Some(Glyph::l),
+ Some(Glyph::m),
+ Some(Glyph::n),
+ Some(Glyph::o),
+ Some(Glyph::p),
+ Some(Glyph::q),
+ Some(Glyph::r),
+ Some(Glyph::s),
+ Some(Glyph::t),
+ Some(Glyph::u),
+ Some(Glyph::v),
+ Some(Glyph::w),
+ Some(Glyph::x),
+ Some(Glyph::y),
+ Some(Glyph::z),
+ Some(Glyph::braceleft),
+ Some(Glyph::bar),
+ Some(Glyph::braceright),
+ Some(Glyph::asciitilde),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::exclamdown),
+ Some(Glyph::cent),
+ Some(Glyph::sterling),
+ Some(Glyph::fraction),
+ Some(Glyph::yen),
+ Some(Glyph::florin),
+ Some(Glyph::section),
+ Some(Glyph::currency),
+ Some(Glyph::quotesingle),
+ Some(Glyph::quotedblleft),
+ Some(Glyph::guillemotleft),
+ Some(Glyph::guilsinglleft),
+ Some(Glyph::guilsinglright),
+ Some(Glyph::fi),
+ Some(Glyph::fl),
+ None,
+ Some(Glyph::endash),
+ Some(Glyph::dagger),
+ Some(Glyph::daggerdbl),
+ Some(Glyph::periodcentered),
+ None,
+ Some(Glyph::paragraph),
+ Some(Glyph::bullet),
+ Some(Glyph::quotesinglbase),
+ Some(Glyph::quotedblbase),
+ Some(Glyph::quotedblright),
+ Some(Glyph::guillemotright),
+ Some(Glyph::ellipsis),
+ Some(Glyph::perthousand),
+ None,
+ Some(Glyph::questiondown),
+ None,
+ Some(Glyph::grave),
+ Some(Glyph::acute),
+ Some(Glyph::circumflex),
+ Some(Glyph::tilde),
+ Some(Glyph::macron),
+ Some(Glyph::breve),
+ Some(Glyph::dotaccent),
+ Some(Glyph::dieresis),
+ None,
+ Some(Glyph::ring),
+ Some(Glyph::cedilla),
+ None,
+ Some(Glyph::hungarumlaut),
+ Some(Glyph::ogonek),
+ Some(Glyph::caron),
+ Some(Glyph::emdash),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::AE),
+ None,
+ Some(Glyph::ordfeminine),
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::Lslash),
+ Some(Glyph::Oslash),
+ Some(Glyph::OE),
+ Some(Glyph::ordmasculine),
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::ae),
+ None,
+ None,
+ None,
+ Some(Glyph::dotlessi),
+ None,
+ None,
+ Some(Glyph::lslash),
+ Some(Glyph::oslash),
+ Some(Glyph::oe),
+ Some(Glyph::germandbls),
+ None,
+ None,
+ None,
+ None,
+];
+
+/// MacExpertEncoding
+#[allow(dead_code)]
+pub const EXPERT_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclamsmall),
+ Some(Glyph::Hungarumlautsmall),
+ None,
+ Some(Glyph::dollaroldstyle),
+ Some(Glyph::dollarsuperior),
+ Some(Glyph::ampersandsmall),
+ Some(Glyph::Acutesmall),
+ Some(Glyph::parenleftsuperior),
+ Some(Glyph::parenrightsuperior),
+ Some(Glyph::twodotenleader),
+ Some(Glyph::onedotenleader),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::fraction),
+ Some(Glyph::zerooldstyle),
+ Some(Glyph::oneoldstyle),
+ Some(Glyph::twooldstyle),
+ Some(Glyph::threeoldstyle),
+ Some(Glyph::fouroldstyle),
+ Some(Glyph::fiveoldstyle),
+ Some(Glyph::sixoldstyle),
+ Some(Glyph::sevenoldstyle),
+ Some(Glyph::eightoldstyle),
+ Some(Glyph::nineoldstyle),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::commasuperior),
+ Some(Glyph::threequartersemdash),
+ Some(Glyph::periodsuperior),
+ Some(Glyph::questionsmall),
+ None,
+ Some(Glyph::asuperior),
+ Some(Glyph::bsuperior),
+ Some(Glyph::centsuperior),
+ Some(Glyph::dsuperior),
+ Some(Glyph::esuperior),
+ None,
+ None,
+ None,
+ Some(Glyph::isuperior),
+ None,
+ None,
+ Some(Glyph::lsuperior),
+ Some(Glyph::msuperior),
+ Some(Glyph::nsuperior),
+ Some(Glyph::osuperior),
+ None,
+ None,
+ Some(Glyph::rsuperior),
+ Some(Glyph::ssuperior),
+ Some(Glyph::tsuperior),
+ None,
+ Some(Glyph::ff),
+ Some(Glyph::fi),
+ Some(Glyph::fl),
+ Some(Glyph::ffi),
+ Some(Glyph::ffl),
+ Some(Glyph::parenleftinferior),
+ None,
+ Some(Glyph::parenrightinferior),
+ Some(Glyph::Circumflexsmall),
+ Some(Glyph::hyphensuperior),
+ Some(Glyph::Gravesmall),
+ Some(Glyph::Asmall),
+ Some(Glyph::Bsmall),
+ Some(Glyph::Csmall),
+ Some(Glyph::Dsmall),
+ Some(Glyph::Esmall),
+ Some(Glyph::Fsmall),
+ Some(Glyph::Gsmall),
+ Some(Glyph::Hsmall),
+ Some(Glyph::Ismall),
+ Some(Glyph::Jsmall),
+ Some(Glyph::Ksmall),
+ Some(Glyph::Lsmall),
+ Some(Glyph::Msmall),
+ Some(Glyph::Nsmall),
+ Some(Glyph::Osmall),
+ Some(Glyph::Psmall),
+ Some(Glyph::Qsmall),
+ Some(Glyph::Rsmall),
+ Some(Glyph::Ssmall),
+ Some(Glyph::Tsmall),
+ Some(Glyph::Usmall),
+ Some(Glyph::Vsmall),
+ Some(Glyph::Wsmall),
+ Some(Glyph::Xsmall),
+ Some(Glyph::Ysmall),
+ Some(Glyph::Zsmall),
+ Some(Glyph::colonmonetary),
+ Some(Glyph::onefitted),
+ Some(Glyph::rupiah),
+ Some(Glyph::Tildesmall),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::exclamdownsmall),
+ Some(Glyph::centoldstyle),
+ Some(Glyph::Lslashsmall),
+ None,
+ None,
+ Some(Glyph::Scaronsmall),
+ Some(Glyph::Zcaronsmall),
+ Some(Glyph::Dieresissmall),
+ Some(Glyph::Brevesmall),
+ Some(Glyph::Caronsmall),
+ None,
+ Some(Glyph::Dotaccentsmall),
+ None,
+ None,
+ Some(Glyph::Macronsmall),
+ None,
+ None,
+ Some(Glyph::figuredash),
+ Some(Glyph::hypheninferior),
+ None,
+ None,
+ Some(Glyph::Ogoneksmall),
+ Some(Glyph::Ringsmall),
+ Some(Glyph::Cedillasmall),
+ None,
+ None,
+ None,
+ Some(Glyph::onequarter),
+ Some(Glyph::onehalf),
+ Some(Glyph::threequarters),
+ Some(Glyph::questiondownsmall),
+ Some(Glyph::oneeighth),
+ Some(Glyph::threeeighths),
+ Some(Glyph::fiveeighths),
+ Some(Glyph::seveneighths),
+ Some(Glyph::onethird),
+ Some(Glyph::twothirds),
+ None,
+ None,
+ Some(Glyph::zerosuperior),
+ Some(Glyph::onesuperior),
+ Some(Glyph::twosuperior),
+ Some(Glyph::threesuperior),
+ Some(Glyph::foursuperior),
+ Some(Glyph::fivesuperior),
+ Some(Glyph::sixsuperior),
+ Some(Glyph::sevensuperior),
+ Some(Glyph::eightsuperior),
+ Some(Glyph::ninesuperior),
+ Some(Glyph::zeroinferior),
+ Some(Glyph::oneinferior),
+ Some(Glyph::twoinferior),
+ Some(Glyph::threeinferior),
+ Some(Glyph::fourinferior),
+ Some(Glyph::fiveinferior),
+ Some(Glyph::sixinferior),
+ Some(Glyph::seveninferior),
+ Some(Glyph::eightinferior),
+ Some(Glyph::nineinferior),
+ Some(Glyph::centinferior),
+ Some(Glyph::dollarinferior),
+ Some(Glyph::periodinferior),
+ Some(Glyph::commainferior),
+ Some(Glyph::Agravesmall),
+ Some(Glyph::Aacutesmall),
+ Some(Glyph::Acircumflexsmall),
+ Some(Glyph::Atildesmall),
+ Some(Glyph::Adieresissmall),
+ Some(Glyph::Aringsmall),
+ Some(Glyph::AEsmall),
+ Some(Glyph::Ccedillasmall),
+ Some(Glyph::Egravesmall),
+ Some(Glyph::Eacutesmall),
+ Some(Glyph::Ecircumflexsmall),
+ Some(Glyph::Edieresissmall),
+ Some(Glyph::Igravesmall),
+ Some(Glyph::Iacutesmall),
+ Some(Glyph::Icircumflexsmall),
+ Some(Glyph::Idieresissmall),
+ Some(Glyph::Ethsmall),
+ Some(Glyph::Ntildesmall),
+ Some(Glyph::Ogravesmall),
+ Some(Glyph::Oacutesmall),
+ Some(Glyph::Ocircumflexsmall),
+ Some(Glyph::Otildesmall),
+ Some(Glyph::Odieresissmall),
+ Some(Glyph::OEsmall),
+ Some(Glyph::Oslashsmall),
+ Some(Glyph::Ugravesmall),
+ Some(Glyph::Uacutesmall),
+ Some(Glyph::Ucircumflexsmall),
+ Some(Glyph::Udieresissmall),
+ Some(Glyph::Yacutesmall),
+ Some(Glyph::Thornsmall),
+ Some(Glyph::Ydieresissmall),
+];
+
+#[allow(dead_code)]
+pub const SYMBOL_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::space),
+ Some(Glyph::exclam),
+ Some(Glyph::universal),
+ Some(Glyph::numbersign),
+ Some(Glyph::existential),
+ Some(Glyph::percent),
+ Some(Glyph::ampersand),
+ Some(Glyph::suchthat),
+ Some(Glyph::parenleft),
+ Some(Glyph::parenright),
+ Some(Glyph::asteriskmath),
+ Some(Glyph::plus),
+ Some(Glyph::comma),
+ Some(Glyph::minus),
+ Some(Glyph::period),
+ Some(Glyph::slash),
+ Some(Glyph::zero),
+ Some(Glyph::one),
+ Some(Glyph::two),
+ Some(Glyph::three),
+ Some(Glyph::four),
+ Some(Glyph::five),
+ Some(Glyph::six),
+ Some(Glyph::seven),
+ Some(Glyph::eight),
+ Some(Glyph::nine),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::less),
+ Some(Glyph::equal),
+ Some(Glyph::greater),
+ Some(Glyph::question),
+ Some(Glyph::congruent),
+ Some(Glyph::Alpha),
+ Some(Glyph::Beta),
+ Some(Glyph::Chi),
+ Some(Glyph::Delta),
+ Some(Glyph::Epsilon),
+ Some(Glyph::Phi),
+ Some(Glyph::Gamma),
+ Some(Glyph::Eta),
+ Some(Glyph::Iota),
+ Some(Glyph::theta1),
+ Some(Glyph::Kappa),
+ Some(Glyph::Lambda),
+ Some(Glyph::Mu),
+ Some(Glyph::Nu),
+ Some(Glyph::Omicron),
+ Some(Glyph::Pi),
+ Some(Glyph::Theta),
+ Some(Glyph::Rho),
+ Some(Glyph::Sigma),
+ Some(Glyph::Tau),
+ Some(Glyph::Upsilon),
+ Some(Glyph::sigma1),
+ Some(Glyph::Omega),
+ Some(Glyph::Xi),
+ Some(Glyph::Psi),
+ Some(Glyph::Zeta),
+ Some(Glyph::bracketleft),
+ Some(Glyph::therefore),
+ Some(Glyph::bracketright),
+ Some(Glyph::perpendicular),
+ Some(Glyph::underscore),
+ Some(Glyph::radicalex),
+ Some(Glyph::alpha),
+ Some(Glyph::beta),
+ Some(Glyph::chi),
+ Some(Glyph::delta),
+ Some(Glyph::epsilon),
+ Some(Glyph::phi),
+ Some(Glyph::gamma),
+ Some(Glyph::eta),
+ Some(Glyph::iota),
+ Some(Glyph::phi2),
+ Some(Glyph::kappa),
+ Some(Glyph::lambda),
+ Some(Glyph::mu),
+ Some(Glyph::nu),
+ Some(Glyph::omicron),
+ Some(Glyph::pi),
+ Some(Glyph::theta),
+ Some(Glyph::rho),
+ Some(Glyph::sigma),
+ Some(Glyph::tau),
+ Some(Glyph::upsilon),
+ Some(Glyph::omega1),
+ Some(Glyph::omega),
+ Some(Glyph::xi),
+ Some(Glyph::psi),
+ Some(Glyph::zeta),
+ Some(Glyph::braceleft),
+ Some(Glyph::bar),
+ Some(Glyph::braceright),
+ Some(Glyph::similar),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::Upsilon1),
+ Some(Glyph::minute),
+ Some(Glyph::lessequal),
+ Some(Glyph::fraction),
+ Some(Glyph::infinity),
+ Some(Glyph::florin),
+ Some(Glyph::club),
+ Some(Glyph::diamond),
+ Some(Glyph::heart),
+ Some(Glyph::spade),
+ Some(Glyph::arrowboth),
+ Some(Glyph::arrowleft),
+ Some(Glyph::arrowup),
+ Some(Glyph::arrowright),
+ Some(Glyph::arrowdown),
+ Some(Glyph::degree),
+ Some(Glyph::plusminus),
+ Some(Glyph::second),
+ Some(Glyph::greaterequal),
+ Some(Glyph::multiply),
+ Some(Glyph::proportional),
+ Some(Glyph::partialdiff),
+ Some(Glyph::bullet),
+ Some(Glyph::divide),
+ Some(Glyph::notequal),
+ Some(Glyph::equivalence),
+ Some(Glyph::approxequal),
+ Some(Glyph::ellipsis),
+ Some(Glyph::arrowvertex),
+ Some(Glyph::arrowhorizex),
+ Some(Glyph::carriagereturn),
+ Some(Glyph::aleph),
+ Some(Glyph::Ifraktur),
+ Some(Glyph::Rfraktur),
+ Some(Glyph::weierstrass),
+ Some(Glyph::circlemultiply),
+ Some(Glyph::circleplus),
+ Some(Glyph::emptyset),
+ Some(Glyph::intersection),
+ Some(Glyph::union),
+ Some(Glyph::propersuperset),
+ Some(Glyph::reflexsuperset),
+ Some(Glyph::notsubset),
+ Some(Glyph::propersubset),
+ Some(Glyph::reflexsubset),
+ Some(Glyph::element),
+ Some(Glyph::notelement),
+ Some(Glyph::angle),
+ Some(Glyph::gradient),
+ Some(Glyph::registerserif),
+ Some(Glyph::copyrightserif),
+ Some(Glyph::trademarkserif),
+ Some(Glyph::product),
+ Some(Glyph::radical),
+ Some(Glyph::dotmath),
+ Some(Glyph::logicalnot),
+ Some(Glyph::logicaland),
+ Some(Glyph::logicalor),
+ Some(Glyph::arrowdblboth),
+ Some(Glyph::arrowdblleft),
+ Some(Glyph::arrowdblup),
+ Some(Glyph::arrowdblright),
+ Some(Glyph::arrowdbldown),
+ Some(Glyph::lozenge),
+ Some(Glyph::angleleft),
+ Some(Glyph::registersans),
+ Some(Glyph::copyrightsans),
+ Some(Glyph::trademarksans),
+ Some(Glyph::summation),
+ Some(Glyph::parenlefttp),
+ Some(Glyph::parenleftex),
+ Some(Glyph::parenleftbt),
+ Some(Glyph::bracketlefttp),
+ Some(Glyph::bracketleftex),
+ Some(Glyph::bracketleftbt),
+ Some(Glyph::bracelefttp),
+ Some(Glyph::braceleftmid),
+ Some(Glyph::braceleftbt),
+ Some(Glyph::braceex),
+ None,
+ Some(Glyph::angleright),
+ Some(Glyph::integral),
+ Some(Glyph::integraltp),
+ Some(Glyph::integralex),
+ Some(Glyph::integralbt),
+ Some(Glyph::parenrighttp),
+ Some(Glyph::parenrightex),
+ Some(Glyph::parenrightbt),
+ Some(Glyph::bracketrighttp),
+ Some(Glyph::bracketrightex),
+ Some(Glyph::bracketrightbt),
+ Some(Glyph::bracerighttp),
+ Some(Glyph::bracerightmid),
+ Some(Glyph::bracerightbt),
+ None,
+];
+
+/// PDFDocEncoding
+#[allow(dead_code)]
+pub const PDF_DOC_ENCODING: CodedCharacterSet = [
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(Glyph::breve),
+ Some(Glyph::caron),
+ Some(Glyph::circumflex),
+ Some(Glyph::dotaccent),
+ Some(Glyph::hungarumlaut),
+ Some(Glyph::ogonek),
+ Some(Glyph::ring),
+ Some(Glyph::tilde),
+ Some(Glyph::space),
+ Some(Glyph::exclam),
+ Some(Glyph::quotedbl),
+ Some(Glyph::numbersign),
+ Some(Glyph::dollar),
+ Some(Glyph::percent),
+ Some(Glyph::ampersand),
+ Some(Glyph::quotesingle),
+ Some(Glyph::parenleft),
+ Some(Glyph::parenright),
+ Some(Glyph::asterisk),
+ Some(Glyph::plus),
+ Some(Glyph::comma),
+ Some(Glyph::hyphen),
+ Some(Glyph::period),
+ Some(Glyph::slash),
+ Some(Glyph::zero),
+ Some(Glyph::one),
+ Some(Glyph::two),
+ Some(Glyph::three),
+ Some(Glyph::four),
+ Some(Glyph::five),
+ Some(Glyph::six),
+ Some(Glyph::seven),
+ Some(Glyph::eight),
+ Some(Glyph::nine),
+ Some(Glyph::colon),
+ Some(Glyph::semicolon),
+ Some(Glyph::less),
+ Some(Glyph::equal),
+ Some(Glyph::greater),
+ Some(Glyph::question),
+ Some(Glyph::at),
+ Some(Glyph::A),
+ Some(Glyph::B),
+ Some(Glyph::C),
+ Some(Glyph::D),
+ Some(Glyph::E),
+ Some(Glyph::F),
+ Some(Glyph::G),
+ Some(Glyph::H),
+ Some(Glyph::I),
+ Some(Glyph::J),
+ Some(Glyph::K),
+ Some(Glyph::L),
+ Some(Glyph::M),
+ Some(Glyph::N),
+ Some(Glyph::O),
+ Some(Glyph::P),
+ Some(Glyph::Q),
+ Some(Glyph::R),
+ Some(Glyph::S),
+ Some(Glyph::T),
+ Some(Glyph::U),
+ Some(Glyph::V),
+ Some(Glyph::W),
+ Some(Glyph::X),
+ Some(Glyph::Y),
+ Some(Glyph::Z),
+ Some(Glyph::bracketleft),
+ Some(Glyph::backslash),
+ Some(Glyph::bracketright),
+ Some(Glyph::asciicircum),
+ Some(Glyph::underscore),
+ Some(Glyph::grave),
+ Some(Glyph::a),
+ Some(Glyph::b),
+ Some(Glyph::c),
+ Some(Glyph::d),
+ Some(Glyph::e),
+ Some(Glyph::f),
+ Some(Glyph::g),
+ Some(Glyph::h),
+ Some(Glyph::i),
+ Some(Glyph::j),
+ Some(Glyph::k),
+ Some(Glyph::l),
+ Some(Glyph::m),
+ Some(Glyph::n),
+ Some(Glyph::o),
+ Some(Glyph::p),
+ Some(Glyph::q),
+ Some(Glyph::r),
+ Some(Glyph::s),
+ Some(Glyph::t),
+ Some(Glyph::u),
+ Some(Glyph::v),
+ Some(Glyph::w),
+ Some(Glyph::x),
+ Some(Glyph::y),
+ Some(Glyph::z),
+ Some(Glyph::braceleft),
+ Some(Glyph::bar),
+ Some(Glyph::braceright),
+ Some(Glyph::asciitilde),
+ None,
+ Some(Glyph::bullet),
+ Some(Glyph::dagger),
+ Some(Glyph::daggerdbl),
+ Some(Glyph::ellipsis),
+ Some(Glyph::emdash),
+ Some(Glyph::endash),
+ Some(Glyph::florin),
+ Some(Glyph::fraction),
+ Some(Glyph::guilsinglleft),
+ Some(Glyph::guilsinglright),
+ Some(Glyph::minus),
+ Some(Glyph::perthousand),
+ Some(Glyph::quotedblbase),
+ Some(Glyph::quotedblleft),
+ Some(Glyph::quotedblright),
+ Some(Glyph::quoteleft),
+ Some(Glyph::quoteright),
+ Some(Glyph::quotesinglbase),
+ Some(Glyph::trademark),
+ Some(Glyph::fi),
+ Some(Glyph::fl),
+ Some(Glyph::Lslash),
+ Some(Glyph::OE),
+ Some(Glyph::Scaron),
+ Some(Glyph::Ydieresis),
+ Some(Glyph::Zcaron),
+ Some(Glyph::dotlessi),
+ Some(Glyph::lslash),
+ Some(Glyph::oe),
+ Some(Glyph::scaron),
+ Some(Glyph::zcaron),
+ None,
+ Some(Glyph::Euro),
+ Some(Glyph::exclamdown),
+ Some(Glyph::cent),
+ Some(Glyph::sterling),
+ Some(Glyph::currency),
+ Some(Glyph::yen),
+ Some(Glyph::brokenbar),
+ Some(Glyph::section),
+ Some(Glyph::dieresis),
+ Some(Glyph::copyright),
+ Some(Glyph::ordfeminine),
+ Some(Glyph::guillemotleft),
+ Some(Glyph::logicalnot),
+ None,
+ Some(Glyph::registered),
+ Some(Glyph::macron),
+ Some(Glyph::degree),
+ Some(Glyph::plusminus),
+ Some(Glyph::twosuperior),
+ Some(Glyph::threesuperior),
+ Some(Glyph::acute),
+ Some(Glyph::mu),
+ Some(Glyph::paragraph),
+ Some(Glyph::periodcentered),
+ Some(Glyph::cedilla),
+ Some(Glyph::onesuperior),
+ Some(Glyph::ordmasculine),
+ Some(Glyph::guillemotright),
+ Some(Glyph::onequarter),
+ Some(Glyph::onehalf),
+ Some(Glyph::threequarters),
+ Some(Glyph::questiondown),
+ Some(Glyph::Agrave),
+ Some(Glyph::Aacute),
+ Some(Glyph::Acircumflex),
+ Some(Glyph::Atilde),
+ Some(Glyph::Adieresis),
+ Some(Glyph::Aring),
+ Some(Glyph::AE),
+ Some(Glyph::Ccedilla),
+ Some(Glyph::Egrave),
+ Some(Glyph::Eacute),
+ Some(Glyph::Ecircumflex),
+ Some(Glyph::Edieresis),
+ Some(Glyph::Igrave),
+ Some(Glyph::Iacute),
+ Some(Glyph::Icircumflex),
+ Some(Glyph::Idieresis),
+ Some(Glyph::Eth),
+ Some(Glyph::Ntilde),
+ Some(Glyph::Ograve),
+ Some(Glyph::Oacute),
+ Some(Glyph::Ocircumflex),
+ Some(Glyph::Otilde),
+ Some(Glyph::Odieresis),
+ Some(Glyph::multiply),
+ Some(Glyph::Oslash),
+ Some(Glyph::Ugrave),
+ Some(Glyph::Uacute),
+ Some(Glyph::Ucircumflex),
+ Some(Glyph::Udieresis),
+ Some(Glyph::Yacute),
+ Some(Glyph::Thorn),
+ Some(Glyph::germandbls),
+ Some(Glyph::agrave),
+ Some(Glyph::aacute),
+ Some(Glyph::acircumflex),
+ Some(Glyph::atilde),
+ Some(Glyph::adieresis),
+ Some(Glyph::aring),
+ Some(Glyph::ae),
+ Some(Glyph::ccedilla),
+ Some(Glyph::egrave),
+ Some(Glyph::eacute),
+ Some(Glyph::ecircumflex),
+ Some(Glyph::edieresis),
+ Some(Glyph::igrave),
+ Some(Glyph::iacute),
+ Some(Glyph::icircumflex),
+ Some(Glyph::idieresis),
+ Some(Glyph::eth),
+ Some(Glyph::ntilde),
+ Some(Glyph::ograve),
+ Some(Glyph::oacute),
+ Some(Glyph::ocircumflex),
+ Some(Glyph::otilde),
+ Some(Glyph::odieresis),
+ Some(Glyph::divide),
+ Some(Glyph::oslash),
+ Some(Glyph::ugrave),
+ Some(Glyph::uacute),
+ Some(Glyph::ucircumflex),
+ Some(Glyph::udieresis),
+ Some(Glyph::yacute),
+ Some(Glyph::thorn),
+ Some(Glyph::ydieresis),
+];
diff --git a/vendor/lopdf/src/encodings/mod.rs b/vendor/lopdf/src/encodings/mod.rs
new file mode 100644
index 000000000..5c731118b
--- /dev/null
+++ b/vendor/lopdf/src/encodings/mod.rs
@@ -0,0 +1,248 @@
+pub mod cmap;
+mod differences;
+mod glyphnames;
+mod mappings;
+
+pub use self::differences::Differences;
+pub use self::glyphnames::Glyph;
+pub use self::mappings::*;
+use crate::Error;
+use crate::Result;
+use crate::parser_aux::substr;
+use cmap::ToUnicodeCMap;
+use encoding_rs::UTF_16BE;
+use log::debug;
+
+pub fn bytes_to_string(encoding: &CodedCharacterSet, bytes: &[u8], out: &mut String) -> Result<()> {
+ for b in bytes {
+ let Some(g) = encoding.get(*b as usize).copied().flatten() else {
+ continue;
+ };
+
+ for ch in char::decode_utf16([g.utf16_code_unit()]).flatten() {
+ out.push(ch);
+ }
+ }
+
+ Ok(())
+}
+
+pub fn string_to_bytes(encoding: &CodedCharacterSet, text: &str) -> Vec<u8> {
+ let mut out = Vec::new();
+ write_to_bytes(encoding, text, &mut out);
+ out
+}
+
+pub fn write_to_bytes(encoding: &CodedCharacterSet, text: &str, out: &mut Vec<u8>) {
+ for c in text.encode_utf16() {
+ let g = Glyph::from_utf16_code_unit(c);
+
+ let Some(n) = encoding.iter().position(|glyph| glyph.is_some_and(|f| f == g)) else {
+ continue;
+ };
+
+ out.push(n as u8);
+ }
+}
+
+pub enum Encoding<'a> {
+ OneByteEncoding(&'a CodedCharacterSet),
+ SimpleEncoding(&'a [u8]),
+ UnicodeMapEncoding(ToUnicodeCMap),
+ Differences(Differences<'a>),
+}
+
+impl std::fmt::Debug for Encoding<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ // UnicodeCMap and Bytes encoding ommitted to not bloat debug log
+ Self::OneByteEncoding(_arg0) => f.debug_tuple("OneByteEncoding").finish(),
+ Self::SimpleEncoding(arg0) => f.debug_tuple("SimpleEncoding").field(arg0).finish(),
+ Self::UnicodeMapEncoding(_arg0) => f.debug_tuple("UnicodeMapEncoding").finish(),
+ Self::Differences(_arg0) => f.debug_tuple("Differences").finish(),
+ }
+ }
+}
+
+impl Encoding<'_> {
+ pub fn bytes_to_string(&self, bytes: &[u8]) -> Result<String> {
+ let mut out = String::new();
+ self.write_to_string(bytes, &mut out)?;
+ Ok(out)
+ }
+
+ pub fn write_to_string(&self, bytes: &[u8], out: &mut String) -> Result<()> {
+ match self {
+ Self::OneByteEncoding(map) => {
+ bytes_to_string(map, bytes, out)?;
+ Ok(())
+ }
+ Self::SimpleEncoding(b"UniGB-UCS2-H") | Self::SimpleEncoding(b"UniGB-UTF16-H") => {
+ out.push_str(UTF_16BE.decode(bytes).0.as_ref());
+ Ok(())
+ }
+ Self::UnicodeMapEncoding(unicode_map) => {
+ let mut output_bytes = Vec::new();
+
+ // source codes can have a variadic length from 1 to 4 bytes
+ let mut bytes_in_considered_code = 0u8;
+ let mut considered_source_code = 0u32;
+ for byte in bytes {
+ if bytes_in_considered_code == 4 {
+ let mut value = unicode_map.get_or_replacement_char(considered_source_code, 4);
+ considered_source_code = 0;
+ bytes_in_considered_code = 0;
+ output_bytes.append(&mut value);
+ }
+ bytes_in_considered_code += 1;
+ considered_source_code = considered_source_code * 256 + *byte as u32;
+ if let Some(mut value) = unicode_map.get(considered_source_code, bytes_in_considered_code) {
+ considered_source_code = 0;
+ bytes_in_considered_code = 0;
+ output_bytes.append(&mut value);
+ }
+ }
+ if bytes_in_considered_code > 0 {
+ let mut value =
+ unicode_map.get_or_replacement_char(considered_source_code, bytes_in_considered_code);
+ output_bytes.append(&mut value);
+ }
+ let utf16_str: Vec<u8> = output_bytes
+ .iter()
+ .flat_map(|it| [(it / 256) as u8, (it % 256) as u8])
+ .collect();
+
+ out.push_str(UTF_16BE.decode(&utf16_str).0.as_ref());
+ Ok(())
+ }
+ Self::SimpleEncoding(b"WinAnsiEncoding") => {
+ bytes_to_string(&WIN_ANSI_ENCODING, bytes, out)?;
+ Ok(())
+ }
+ Self::SimpleEncoding(_) => Err(Error::CharacterEncoding),
+ Self::Differences(differences) => differences.bytes_to_string(bytes, out),
+ }
+ }
+
+ pub fn string_to_bytes(&self, text: &str) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ self.write_to_bytes(text, &mut bytes);
+ bytes
+ }
+
+ pub fn write_to_bytes(&self, text: &str, out: &mut Vec<u8>) {
+ match self {
+ Self::OneByteEncoding(map) => write_to_bytes(map, text, out),
+ Self::SimpleEncoding(b"UniGB-UCS2-H") | Self::SimpleEncoding(b"UniGB-UTF16-H") => {
+ encode_utf16_be(text, out)
+ }
+ Self::SimpleEncoding(b"WinAnsiEncoding") => write_to_bytes(&WIN_ANSI_ENCODING, text, out),
+ Self::UnicodeMapEncoding(unicode_map) => {
+ let mut i = 0;
+ while i < text.chars().count() {
+ let current_unicode_seq: Vec<u16> = substr(text, i, 1).encode_utf16().collect();
+
+ if let Some(entries) = unicode_map.get_source_codes_for_unicode(&current_unicode_seq) {
+ if let Some(entry) = entries.first() {
+ // TODO: Add logic to pick the best entry if multiple
+ let mut bytes_for_code = Vec::new();
+ let val = entry.source_code;
+ match entry.code_len {
+ 1 => bytes_for_code.push(val as u8),
+ 2 => bytes_for_code.extend_from_slice(&(val as u16).to_be_bytes()),
+ 3 => {
+ bytes_for_code.push((val >> 16) as u8);
+ bytes_for_code.push((val >> 8) as u8);
+ bytes_for_code.push(val as u8);
+ }
+ 4 => bytes_for_code.extend_from_slice(&val.to_be_bytes()),
+ _ => { /* Should not happen */ }
+ }
+ out.extend(bytes_for_code);
+ } else {
+ // No specific entry, handle as unmappable
+ log::warn!(
+ "Unicode sequence {current_unicode_seq:04X?} found in map but no entries, skipping."
+ );
+ }
+ } else {
+ // Character or sequence not found in CMap
+ log::warn!(
+ "Unicode sequence {current_unicode_seq:04X?} not found in ToUnicode CMap, skipping."
+ );
+ }
+ i += 1;
+ }
+ }
+ Self::SimpleEncoding(_) => {
+ debug!("Unknown encoding used to encode text {self:?}");
+ out.extend_from_slice(text.as_bytes());
+ }
+ Self::Differences(differences) => {
+ differences.string_to_bytes(text, out);
+ }
+ }
+ }
+}
+
+/// Encodes the given `str` to UTF-16BE.
+/// The recommended way to encode text strings, as it supports all of
+/// unicode and all major PDF readers support it.
+pub fn encode_utf16_be(text: &str, out: &mut Vec<u8>) {
+ // Prepend BOM to the mark string as UTF-16BE encoded.
+ let bom_be: [u8; 2] = [0xFE, 0xFF];
+ out.extend_from_slice(&bom_be);
+ out.extend(text.encode_utf16().flat_map(|b| b.to_be_bytes()));
+}
+
+/// Encodes the given `str` to UTF-8. This method of encoding text strings
+/// is first specified in PDF2.0 and reader support is still lacking
+/// (notably, Adobe Acrobat Reader doesn't support it at the time of writing).
+/// Thus, using it is **NOT RECOMMENDED**.
+pub fn encode_utf8(text: &str) -> Vec<u8> {
+ // Prepend BOM to the mark string as UTF-8 encoded.
+ let mut bytes = vec![0xEF, 0xBB, 0xBF];
+ bytes.extend(text.bytes());
+ bytes
+}
+
+#[cfg(test)]
+mod tests {
+
+ use super::*;
+
+ #[test]
+ fn unicode_with_2byte_code_does_not_convert_single_bytes() {
+ let mut cmap = ToUnicodeCMap::new();
+
+ cmap.put(0x0000, 0x0002, 2, cmap::BfRangeTarget::UTF16CodePoint { offset: 0 });
+ cmap.put(0x0024, 0x0025, 2, cmap::BfRangeTarget::UTF16CodePoint { offset: 0 });
+
+ let bytes: [u8; 2] = [0x00, 0x24];
+
+ let result = Encoding::UnicodeMapEncoding(cmap).bytes_to_string(&bytes);
+
+ assert_eq!(result.unwrap(), "\u{0024}");
+ }
+
+ #[test]
+ fn winansi_bytes_to_string() {
+ // 0xe9 = é in WinAnsi, 0xfc = ü, 0xdf = ß
+ let bytes = [0x41, 0xe9, 0x42, 0xfc, 0xdf]; // AéBüß
+ let result = Encoding::SimpleEncoding(b"WinAnsiEncoding")
+ .bytes_to_string(&bytes)
+ .expect("WinAnsi decode should succeed");
+ assert_eq!(result, "AéBüß");
+ }
+
+ #[test]
+ fn winansi_string_to_bytes() {
+ let text = "Sébastien 0,019€ ü ÄÖÜ ß";
+ let bytes = Encoding::SimpleEncoding(b"WinAnsiEncoding").string_to_bytes(text);
+ // Round-trip: decode the bytes back via the same encoding
+ let decoded = Encoding::OneByteEncoding(&WIN_ANSI_ENCODING)
+ .bytes_to_string(&bytes)
+ .expect("WinAnsi decode should succeed");
+ assert_eq!(decoded, text);
+ }
+}
diff --git a/vendor/lopdf/src/encryption.rs b/vendor/lopdf/src/encryption.rs
new file mode 100644
index 000000000..b580584b2
--- /dev/null
+++ b/vendor/lopdf/src/encryption.rs
@@ -0,0 +1,1048 @@
+mod algorithms;
+pub mod crypt_filters;
+mod pkcs5;
+mod rc4;
+
+use crate::{Dictionary, Document, Error, Object, ObjectId};
+use bitflags::bitflags;
+use crypt_filters::*;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+use thiserror::Error;
+
+pub use algorithms::PasswordAlgorithm;
+
+#[derive(Error, Debug)]
+pub enum DecryptionError {
+ #[error("the /Encrypt dictionary is missing")]
+ MissingEncryptDictionary,
+ #[error("missing encryption version")]
+ MissingVersion,
+ #[error("missing encryption revision")]
+ MissingRevision,
+ #[error("missing the owner password (/O)")]
+ MissingOwnerPassword,
+ #[error("missing the user password (/U)")]
+ MissingUserPassword,
+ #[error("missing the permissions field (/P)")]
+ MissingPermissions,
+ #[error("missing the file /ID elements")]
+ MissingFileID,
+
+ #[error("invalid hash length")]
+ InvalidHashLength,
+ #[error("invalid key length")]
+ InvalidKeyLength,
+ #[error("invalid ciphertext length")]
+ InvalidCipherTextLength,
+ #[error("invalid permission length")]
+ InvalidPermissionLength,
+ #[error("invalid version")]
+ InvalidVersion,
+ #[error("invalid revision")]
+ InvalidRevision,
+ // Used generically when the object type violates the spec
+ #[error("unexpected type; document does not comply with the spec")]
+ InvalidType,
+
+ #[error("the object is not capable of being decrypted")]
+ NotDecryptable,
+ #[error("the supplied password is incorrect")]
+ IncorrectPassword,
+
+ #[error("the document uses an encryption scheme that is not implemented in lopdf")]
+ UnsupportedEncryption,
+ #[error("the encryption version is not implemented in lopdf")]
+ UnsupportedVersion,
+ #[error("the encryption revision is not implemented in lopdf")]
+ UnsupportedRevision,
+
+ #[error(transparent)]
+ StringPrep(#[from] stringprep::Error),
+ #[error("invalid padding encountered when decrypting, key might be incorrect")]
+ Padding,
+}
+
+bitflags! {
+ #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
+ pub struct Permissions: u64 {
+ /// (Security handlers of revision 2) Print the document.
+ /// (Security handlers of revision 3 or greater) Print the document (possibly not at the
+ /// highest quality level, depending on whether [`Permissions::PRINTABLE_IN_HIGH_QUALITY`]
+ /// is also set).
+ const PRINTABLE = 1 << 2;
+
+ /// Modify the contents of the document by operations other than those controlled by
+ /// [`Permissions::ANNOTABLE`], [`Permissions::FILLABLE`] and [`Permissions::ASSEMBLABLE`].
+ const MODIFIABLE = 1 << 3;
+
+ /// Copy or otherwise extract text and graphics from the document. However, for the limited
+ /// purpose of providing this content to assistive technology, a PDF reader should behave
+ /// as if this bit was set to 1.
+ const COPYABLE = 1 << 4;
+
+ /// Add or modify text annotations, fill in interactive form fields, and if
+ /// [`Permissions::MODIFIABLE`] is also set, create or modify interactive form fields
+ /// (including signature fields).
+ const ANNOTABLE = 1 << 5;
+
+ /// Fill in existing interactive fields (including signature fields), even if
+ /// [`Permissions::ANNOTABLE`] is clear.
+ const FILLABLE = 1 << 8;
+
+ /// Copy or otherwise extract text and graphics from the document for the purpose of
+ /// providing this content to assistive technology.
+ ///
+ /// Deprecated since PDF 2.0: must always be set for backward compatibility with PDF
+ /// viewers following earlier specifications.
+ const COPYABLE_FOR_ACCESSIBILITY = 1 << 9;
+
+ /// (Security handlers of revision 3 or greater) Assemble the document (insert, rotate, or
+ /// delete pages and create document outline items or thumbnail images), even if
+ /// [`Permissions::MODIFIABLE`] is not set.
+ const ASSEMBLABLE = 1 << 10;
+
+ /// (Security handlers of revision 3 or greater) Print the document to a representation
+ /// from which a faithful copy of the PDF content could be generated, based on an
+ /// implementation-dependent algorithm. When this bit is clear (and
+ /// [`Permissions::PRINTABLE`] is set), printing shall be limited to a low-level
+ /// representation of the appearance, possibly of degraded quality.
+ const PRINTABLE_IN_HIGH_QUALITY = 1 << 11;
+ }
+}
+
+impl Default for Permissions {
+ fn default() -> Self {
+ Self::all()
+ }
+}
+
+impl Permissions {
+ fn correct_bits(self) -> Self {
+ let mut bits = self.bits();
+
+ // 7-8: Reserved. Must be 1.
+ bits |= 0b11 << 6;
+
+ // 13-32: Reserved. Must be 1.
+ bits |= 0b1111 << 12 | 0xffff << 16;
+
+ // Extend the permissions (contents of the P integer) to 64 bits by setting the upper 32
+ // bits to all 1s.
+ bits |= 0xffffffff << 32;
+
+ Permissions::from_bits_retain(bits)
+ }
+}
+
+#[derive(Clone, Debug)]
+pub enum EncryptionVersion<'a> {
+ /// (PDF 1.4; deprecated in PDF 2.0) Indicates the use of encryption of data using the RC4 or
+ /// AES algorithms with a file encryption key length of 40 bits.
+ V1 {
+ document: &'a Document,
+ owner_password: &'a str,
+ user_password: &'a str,
+ permissions: Permissions,
+ },
+ /// (PDF 1.4; deprecated in PDF 2.0) Indicates the use of encryption of data using the RC4 or
+ /// AES algorithms but permitting file encryption key lengths greater or 40 bits.
+ V2 {
+ document: &'a Document,
+ owner_password: &'a str,
+ user_password: &'a str,
+ key_length: usize,
+ permissions: Permissions,
+ },
+ /// (PDF 1.5; deprecated in PDF 2.0) The security handler defines the use of encryption and
+ /// decryption in the document, using the rules specified by the CF, StmF and StrF entries
+ /// using encryption of data using the RC4 or AES algorithms (deprecated in PDF 2.0) with a
+ /// file encryption key length of 128 bits.
+ V4 {
+ document: &'a Document,
+ encrypt_metadata: bool,
+ crypt_filters: BTreeMap<Vec<u8>, Arc<dyn CryptFilter>>,
+ stream_filter: Vec<u8>,
+ string_filter: Vec<u8>,
+ owner_password: &'a str,
+ user_password: &'a str,
+ permissions: Permissions,
+ },
+ /// (PDF 2.0; deprecated in PDF 2.0) Shall not be used. This value was used by a deprecated
+ /// proprietary Adobe extension.
+ ///
+ /// This exists for testing purposes to guarantee improved compatibility.
+ #[deprecated(
+ note = "R5 is a proprietary Adobe extension and should not be used in newly produced documents other than for testing purposes."
+ )]
+ R5 {
+ encrypt_metadata: bool,
+ crypt_filters: BTreeMap<Vec<u8>, Arc<dyn CryptFilter>>,
+ file_encryption_key: &'a [u8],
+ stream_filter: Vec<u8>,
+ string_filter: Vec<u8>,
+ owner_password: &'a str,
+ user_password: &'a str,
+ permissions: Permissions,
+ },
+ /// (PDF 2.0) The security handler defines the use of encryption and decryption in the
+ /// document, using the rules specified by the CF, StmF, StrF and EFF entries using encryption
+ /// of data using the AES algorithms with a file encryption key length of 256 bits.
+ V5 {
+ encrypt_metadata: bool,
+ crypt_filters: BTreeMap<Vec<u8>, Arc<dyn CryptFilter>>,
+ file_encryption_key: &'a [u8],
+ stream_filter: Vec<u8>,
+ string_filter: Vec<u8>,
+ owner_password: &'a str,
+ user_password: &'a str,
+ permissions: Permissions,
+ },
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct EncryptionState {
+ pub(crate) version: i64,
+ pub(crate) revision: i64,
+ pub(crate) key_length: Option<usize>,
+ pub(crate) encrypt_metadata: bool,
+ pub(crate) crypt_filters: BTreeMap<Vec<u8>, Arc<dyn CryptFilter>>,
+ pub(crate) file_encryption_key: Vec<u8>,
+ pub(crate) stream_filter: Vec<u8>,
+ pub(crate) string_filter: Vec<u8>,
+ pub(crate) owner_value: Vec<u8>,
+ pub(crate) owner_encrypted: Vec<u8>,
+ pub(crate) user_value: Vec<u8>,
+ pub(crate) user_encrypted: Vec<u8>,
+ pub(crate) permissions: Permissions,
+ pub(crate) permission_encrypted: Vec<u8>,
+ /// Object id of the `/Encrypt` dictionary in the previous revision, recorded
+ /// during `Document::decrypt_raw` before the reference is stripped from the
+ /// trailer. Used by `IncrementalDocument` to restore the `/Encrypt` reference
+ /// in the appended trailer.
+ pub(crate) encrypt_object_id: Option<ObjectId>,
+}
+
+impl TryFrom<EncryptionVersion<'_>> for EncryptionState {
+ type Error = Error;
+
+ fn try_from(version: EncryptionVersion) -> Result<EncryptionState, Self::Error> {
+ match version {
+ EncryptionVersion::V1 {
+ document,
+ owner_password,
+ user_password,
+ permissions,
+ } => {
+ let permissions = permissions.correct_bits();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ length: None,
+ version: 1,
+ revision: 2,
+ permissions,
+ ..Default::default()
+ };
+
+ let owner_password = algorithm.sanitize_password_r4(owner_password)?;
+ let user_password = algorithm.sanitize_password_r4(user_password)?;
+
+ algorithm.owner_value =
+ algorithm.compute_hashed_owner_password_r4(Some(&owner_password), &user_password)?;
+
+ algorithm.user_value = algorithm.compute_hashed_user_password_r2(document, &user_password)?;
+
+ let file_encryption_key = algorithm.compute_file_encryption_key_r4(document, &user_password)?;
+
+ Ok(Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ file_encryption_key,
+ owner_value: algorithm.owner_value,
+ user_value: algorithm.user_value,
+ permissions: algorithm.permissions,
+ ..Default::default()
+ })
+ }
+ EncryptionVersion::V2 {
+ document,
+ owner_password,
+ user_password,
+ key_length,
+ permissions,
+ } => {
+ let permissions = permissions.correct_bits();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ length: Some(key_length),
+ version: 2,
+ revision: 3,
+ permissions,
+ ..Default::default()
+ };
+
+ let owner_password = algorithm.sanitize_password_r4(owner_password)?;
+ let user_password = algorithm.sanitize_password_r4(user_password)?;
+
+ algorithm.owner_value =
+ algorithm.compute_hashed_owner_password_r4(Some(&owner_password), &user_password)?;
+
+ algorithm.user_value = algorithm.compute_hashed_user_password_r3_r4(document, &user_password)?;
+
+ let file_encryption_key = algorithm.compute_file_encryption_key_r4(document, &user_password)?;
+
+ Ok(Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ file_encryption_key,
+ owner_value: algorithm.owner_value,
+ user_value: algorithm.user_value,
+ permissions,
+ ..Default::default()
+ })
+ }
+ EncryptionVersion::V4 {
+ document,
+ encrypt_metadata,
+ crypt_filters,
+ stream_filter,
+ string_filter,
+ owner_password,
+ user_password,
+ permissions,
+ } => {
+ let permissions = permissions.correct_bits();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata,
+ length: Some(128),
+ version: 4,
+ revision: 4,
+ permissions,
+ ..Default::default()
+ };
+
+ let owner_password = algorithm.sanitize_password_r4(owner_password)?;
+ let user_password = algorithm.sanitize_password_r4(user_password)?;
+
+ algorithm.owner_value =
+ algorithm.compute_hashed_owner_password_r4(Some(&owner_password), &user_password)?;
+
+ algorithm.user_value = algorithm.compute_hashed_user_password_r3_r4(document, &user_password)?;
+
+ let file_encryption_key = algorithm.compute_file_encryption_key_r4(document, &user_password)?;
+
+ Ok(Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ file_encryption_key,
+ crypt_filters,
+ stream_filter,
+ string_filter,
+ owner_value: algorithm.owner_value,
+ user_value: algorithm.user_value,
+ permissions: algorithm.permissions,
+ ..Default::default()
+ })
+ }
+ #[allow(deprecated)]
+ EncryptionVersion::R5 {
+ encrypt_metadata,
+ crypt_filters,
+ file_encryption_key,
+ stream_filter,
+ string_filter,
+ owner_password,
+ user_password,
+ permissions,
+ } => {
+ if file_encryption_key.len() != 32 {
+ return Err(DecryptionError::InvalidKeyLength)?;
+ }
+
+ let permissions = permissions.correct_bits();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata,
+ version: 5,
+ revision: 5,
+ permissions,
+ ..Default::default()
+ };
+
+ let owner_password = algorithm.sanitize_password_r6(owner_password)?;
+ let user_password = algorithm.sanitize_password_r6(user_password)?;
+
+ let (user_value, user_encrypted) =
+ algorithm.compute_hashed_user_password_r6(file_encryption_key, user_password)?;
+
+ algorithm.user_value = user_value;
+ algorithm.user_encrypted = user_encrypted;
+
+ let (owner_value, owner_encrypted) =
+ algorithm.compute_hashed_owner_password_r6(file_encryption_key, owner_password)?;
+
+ algorithm.owner_value = owner_value;
+ algorithm.owner_encrypted = owner_encrypted;
+
+ algorithm.permission_encrypted = algorithm.compute_permissions(file_encryption_key)?;
+
+ Ok(Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ crypt_filters,
+ file_encryption_key: file_encryption_key.to_vec(),
+ stream_filter,
+ string_filter,
+ owner_value: algorithm.owner_value,
+ owner_encrypted: algorithm.owner_encrypted,
+ user_value: algorithm.user_value,
+ user_encrypted: algorithm.user_encrypted,
+ permissions: algorithm.permissions,
+ permission_encrypted: algorithm.permission_encrypted,
+ encrypt_object_id: None,
+ })
+ }
+ EncryptionVersion::V5 {
+ encrypt_metadata,
+ crypt_filters,
+ file_encryption_key,
+ stream_filter,
+ string_filter,
+ owner_password,
+ user_password,
+ permissions,
+ } => {
+ if file_encryption_key.len() != 32 {
+ return Err(DecryptionError::InvalidKeyLength)?;
+ }
+
+ let permissions = permissions.correct_bits();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata,
+ version: 5,
+ revision: 6,
+ permissions,
+ ..Default::default()
+ };
+
+ let owner_password = algorithm.sanitize_password_r6(owner_password)?;
+ let user_password = algorithm.sanitize_password_r6(user_password)?;
+
+ let (user_value, user_encrypted) =
+ algorithm.compute_hashed_user_password_r6(file_encryption_key, user_password)?;
+
+ algorithm.user_value = user_value;
+ algorithm.user_encrypted = user_encrypted;
+
+ let (owner_value, owner_encrypted) =
+ algorithm.compute_hashed_owner_password_r6(file_encryption_key, owner_password)?;
+
+ algorithm.owner_value = owner_value;
+ algorithm.owner_encrypted = owner_encrypted;
+
+ algorithm.permission_encrypted = algorithm.compute_permissions(file_encryption_key)?;
+
+ Ok(Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ crypt_filters,
+ file_encryption_key: file_encryption_key.to_vec(),
+ stream_filter,
+ string_filter,
+ owner_value: algorithm.owner_value,
+ owner_encrypted: algorithm.owner_encrypted,
+ user_value: algorithm.user_value,
+ user_encrypted: algorithm.user_encrypted,
+ permissions: algorithm.permissions,
+ permission_encrypted: algorithm.permission_encrypted,
+ encrypt_object_id: None,
+ })
+ }
+ }
+ }
+}
+
+impl EncryptionState {
+ pub fn version(&self) -> i64 {
+ self.version
+ }
+
+ pub fn revision(&self) -> i64 {
+ self.revision
+ }
+
+ pub fn key_length(&self) -> Option<usize> {
+ self.key_length
+ }
+
+ pub fn encrypt_metadata(&self) -> bool {
+ self.encrypt_metadata
+ }
+
+ pub fn crypt_filters(&self) -> &BTreeMap<Vec<u8>, Arc<dyn CryptFilter>> {
+ &self.crypt_filters
+ }
+
+ pub fn file_encryption_key(&self) -> &[u8] {
+ self.file_encryption_key.as_ref()
+ }
+
+ pub fn default_stream_filter(&self) -> &[u8] {
+ self.stream_filter.as_ref()
+ }
+
+ pub fn default_string_filter(&self) -> &[u8] {
+ self.string_filter.as_ref()
+ }
+
+ pub fn owner_value(&self) -> &[u8] {
+ self.owner_value.as_ref()
+ }
+
+ pub fn owner_encrypted(&self) -> &[u8] {
+ self.owner_encrypted.as_ref()
+ }
+
+ pub fn user_value(&self) -> &[u8] {
+ self.user_value.as_ref()
+ }
+
+ pub fn user_encrypted(&self) -> &[u8] {
+ self.user_encrypted.as_ref()
+ }
+
+ pub fn permissions(&self) -> Permissions {
+ self.permissions
+ }
+
+ pub fn permission_encrypted(&self) -> &[u8] {
+ self.permission_encrypted.as_ref()
+ }
+
+ /// Object id of the original `/Encrypt` dictionary, when known. This is
+ /// recorded during `Document::decrypt_raw`; the dictionary bytes themselves
+ /// are left intact in the previous revision so that an incremental save can
+ /// point back at them via `/Encrypt N G R` without re-emitting the dictionary.
+ pub fn encrypt_object_id(&self) -> Option<ObjectId> {
+ self.encrypt_object_id
+ }
+
+ pub fn decode<P>(document: &Document, password: P) -> Result<Self, Error>
+ where
+ P: AsRef<[u8]>,
+ {
+ if !document.is_encrypted() {
+ return Err(Error::NotEncrypted);
+ }
+
+ // The name of the preferred security handler for this document. It shall be the name of
+ // the security handler that was used to encrypt the document.
+ //
+ // Standard shall be the name of the built-in password-based security handler.
+ let filter = document
+ .get_encrypted()
+ .and_then(|dict| dict.get(b"Filter"))
+ .and_then(|object| object.as_name())
+ .map_err(|_| Error::DictKey("Filter".to_string()))?;
+
+ if filter != b"Standard" {
+ return Err(Error::UnsupportedSecurityHandler(filter.to_vec()));
+ }
+
+ let algorithm = PasswordAlgorithm::try_from(document)?;
+ let file_encryption_key = algorithm.compute_file_encryption_key(document, password)?;
+
+ let mut crypt_filters = document.get_crypt_filters();
+
+ // CF is meaningful only when the value of V is 4 (PDF 1.5) or 5 (PDF 2.0).
+ if algorithm.version < 4 {
+ crypt_filters.clear();
+ }
+
+ let mut state = Self {
+ version: algorithm.version,
+ revision: algorithm.revision,
+ key_length: algorithm.length,
+ encrypt_metadata: algorithm.encrypt_metadata,
+ crypt_filters,
+ file_encryption_key,
+ owner_value: algorithm.owner_value,
+ owner_encrypted: algorithm.owner_encrypted,
+ user_value: algorithm.user_value,
+ user_encrypted: algorithm.user_encrypted,
+ permissions: algorithm.permissions,
+ permission_encrypted: algorithm.permission_encrypted,
+ ..Default::default()
+ };
+
+ // StmF and StrF are meaningful only when the value of V is 4 (PDF 1.5) or 5 (PDF 2.0).
+ if algorithm.version == 4 || algorithm.version == 5 {
+ if let Ok(stream_filter) = document
+ .get_encrypted()
+ .and_then(|dict| dict.get(b"StmF"))
+ .and_then(|object| object.as_name())
+ {
+ state.stream_filter = stream_filter.to_vec();
+ }
+
+ if let Ok(string_filter) = document
+ .get_encrypted()
+ .and_then(|dict| dict.get(b"StrF"))
+ .and_then(|object| object.as_name())
+ {
+ state.string_filter = string_filter.to_vec();
+ }
+ }
+
+ Ok(state)
+ }
+
+ pub fn encode(&self) -> Result<Dictionary, DecryptionError> {
+ let mut encrypted = Dictionary::new();
+
+ encrypted.set(b"Filter", Object::Name(b"Standard".to_vec()));
+
+ encrypted.set(b"V", Object::Integer(self.version));
+ encrypted.set(b"R", Object::Integer(self.revision));
+
+ if let Some(key_length) = self.key_length {
+ encrypted.set(b"Length", Object::Integer(key_length as i64));
+ }
+
+ // Optional; meaningful only when the value of V is 4 (PDF 1.5) or 5 (PDF 2.0)). Indicates
+ // whether the document-level metadata stream shall be encrypted. Default value: true.
+ if self.version >= 4 {
+ encrypted.set(b"EncryptMetadata", Object::Boolean(self.encrypt_metadata));
+ }
+
+ encrypted.set(b"O", Object::string_literal(self.owner_value.clone()));
+ encrypted.set(b"U", Object::string_literal(self.user_value.clone()));
+ encrypted.set(b"P", Object::Integer(self.permissions.bits() as i64));
+
+ if self.revision >= 4 {
+ let mut filters = Dictionary::new();
+
+ for (name, crypt_filter) in &self.crypt_filters {
+ let mut filter = Dictionary::new();
+
+ filter.set(b"Type", Object::Name(b"CryptFilter".to_vec()));
+ filter.set(b"CFM", Object::Name(crypt_filter.method().to_vec()));
+
+ filters.set(name.to_vec(), Object::Dictionary(filter));
+ }
+
+ encrypted.set(b"CF", Object::Dictionary(filters));
+ encrypted.set(b"StmF", Object::Name(self.stream_filter.clone()));
+ encrypted.set(b"StrF", Object::Name(self.string_filter.clone()));
+ }
+
+ if self.revision >= 5 {
+ encrypted.set(b"OE", Object::string_literal(self.owner_encrypted.clone()));
+ encrypted.set(b"UE", Object::string_literal(self.user_encrypted.clone()));
+ encrypted.set(b"Perms", Object::string_literal(self.permission_encrypted.clone()));
+ }
+
+ Ok(encrypted)
+ }
+
+ pub fn get_stream_filter(&self) -> Arc<dyn CryptFilter> {
+ self.crypt_filters
+ .get(&self.stream_filter)
+ .cloned()
+ .unwrap_or(Arc::new(Rc4CryptFilter))
+ }
+
+ pub fn get_string_filter(&self) -> Arc<dyn CryptFilter> {
+ self.crypt_filters
+ .get(&self.string_filter)
+ .cloned()
+ .unwrap_or(Arc::new(Rc4CryptFilter))
+ }
+}
+
+/// Encrypts `obj`.
+pub fn encrypt_object(state: &EncryptionState, obj_id: ObjectId, obj: &mut Object) -> Result<(), DecryptionError> {
+ // The cross-reference stream shall not be encrypted and strings appearing in the
+ // cross-reference stream dictionary shall not be encrypted.
+ let is_xref_stream = obj
+ .as_stream()
+ .map(|stream| stream.dict.has_type(b"XRef"))
+ .unwrap_or(false);
+
+ if is_xref_stream {
+ return Ok(());
+ }
+
+ // The Metadata stream shall only be encrypted if EncryptMetadata is set to true.
+ if obj.type_name().ok() == Some(b"Metadata") && !state.encrypt_metadata {
+ return Ok(());
+ }
+
+ // A stream filter type, the Crypt filter can be specified for any stream in the document to
+ // override the default filter for streams. The stream's DecodeParms entry shall contain a
+ // Crypt filter decode parameters dictionary whose Name entry specifies the particular crypt
+ // filter that shell be used (if missing, Identity is used).
+ let override_crypt_filter = obj
+ .as_stream()
+ .ok()
+ .filter(|stream| {
+ stream
+ .filters()
+ .map(|filters| filters.contains(&&b"Crypt"[..]))
+ .unwrap_or(false)
+ })
+ .and_then(|stream| stream.dict.get(b"DecodeParms").ok())
+ .and_then(|object| object.as_dict().ok())
+ .map(|dict| {
+ dict.get(b"Name")
+ .and_then(|object| object.as_name())
+ .ok()
+ .and_then(|name| state.crypt_filters.get(name).cloned())
+ .unwrap_or(Arc::new(IdentityCryptFilter))
+ });
+
+ // Retrieve the plaintext and the crypt filter to use to decrypt the ciphertext from the given
+ // object.
+ let (mut crypt_filter, plaintext) = match obj {
+ // Encryption applies to all strings and streams in the document's PDF file, i.e., we have to
+ // recursively process array and dictionary objects to decrypt any string and stream objects
+ // stored inside of those.
+ Object::Array(objects) => {
+ for obj in objects {
+ encrypt_object(state, obj_id, obj)?;
+ }
+
+ return Ok(());
+ }
+ Object::Dictionary(objects) => {
+ for (_, obj) in objects.iter_mut() {
+ encrypt_object(state, obj_id, obj)?;
+ }
+
+ return Ok(());
+ }
+ // Encryption applies to all strings and streams in the document's PDF file. We return the
+ // crypt filter and the content here.
+ Object::String(content, _) => (state.get_string_filter(), &*content),
+ Object::Stream(stream) => (state.get_stream_filter(), &stream.content),
+ // Encryption is not applied to other object types such as integers and boolean values.
+ _ => {
+ return Ok(());
+ }
+ };
+
+ // If the stream object specifies its own crypt filter, override the default one with the one
+ // from this stream object.
+ if let Some(filter) = override_crypt_filter {
+ crypt_filter = filter;
+ }
+
+ // Compute the key from the original file encryption key and the object identifier to use for
+ // the corresponding object.
+ let key = crypt_filter.compute_key(&state.file_encryption_key, obj_id)?;
+
+ // Encrypt the plaintext.
+ let ciphertext = crypt_filter.encrypt(&key, plaintext)?;
+
+ // Store the ciphertext in the object.
+ match obj {
+ Object::Stream(stream) => stream.set_content(ciphertext),
+ Object::String(content, _) => *content = ciphertext,
+ _ => (),
+ }
+
+ Ok(())
+}
+
+/// Decrypts `obj`.
+pub fn decrypt_object(state: &EncryptionState, obj_id: ObjectId, obj: &mut Object) -> Result<(), DecryptionError> {
+ // The cross-reference stream shall not be encrypted and strings appearing in the
+ // cross-reference stream dictionary shall not be encrypted.
+ let is_xref_stream = obj
+ .as_stream()
+ .map(|stream| stream.dict.has_type(b"XRef"))
+ .unwrap_or(false);
+
+ if is_xref_stream {
+ return Ok(());
+ }
+
+ // The Metadata stream shall only be encrypted if EncryptMetadata is set to true.
+ if obj.type_name().ok() == Some(b"Metadata") && !state.encrypt_metadata {
+ return Ok(());
+ }
+
+ // A stream filter type, the Crypt filter can be specified for any stream in the document to
+ // override the default filter for streams. The stream's DecodeParms entry shall contain a
+ // Crypt filter decode parameters dictionary whose Name entry specifies the particular crypt
+ // filter that shell be used (if missing, Identity is used).
+ let override_crypt_filter = obj
+ .as_stream()
+ .ok()
+ .filter(|stream| {
+ stream
+ .filters()
+ .map(|filters| filters.contains(&&b"Crypt"[..]))
+ .unwrap_or(false)
+ })
+ .and_then(|stream| stream.dict.get(b"DecodeParms").ok())
+ .and_then(|object| object.as_dict().ok())
+ .map(|dict| {
+ dict.get(b"Name")
+ .and_then(|object| object.as_name())
+ .ok()
+ .and_then(|name| state.crypt_filters.get(name).cloned())
+ .unwrap_or(Arc::new(IdentityCryptFilter))
+ });
+
+ // Retrieve the ciphertext and the crypt filter to use to decrypt the ciphertext from the given
+ // object.
+ let (mut crypt_filter, ciphertext) = match obj {
+ // Encryption applies to all strings and streams in the document's PDF file, i.e., we have to
+ // recursively process array and dictionary objects to decrypt any string and stream objects
+ // stored inside of those.
+ Object::Array(objects) => {
+ for obj in objects {
+ decrypt_object(state, obj_id, obj)?;
+ }
+
+ return Ok(());
+ }
+ Object::Dictionary(objects) => {
+ for (_, obj) in objects.iter_mut() {
+ decrypt_object(state, obj_id, obj)?;
+ }
+
+ return Ok(());
+ }
+ // Encryption applies to all strings and streams in the document's PDF file. We return the
+ // crypt filter and the content here.
+ Object::String(content, _) => (state.get_string_filter(), &*content),
+ Object::Stream(stream) => (state.get_stream_filter(), &stream.content),
+ // Encryption is not applied to other object types such as integers and boolean values.
+ _ => {
+ return Ok(());
+ }
+ };
+
+ // If the stream object specifies its own crypt filter, override the default one with the one
+ // from this stream object.
+ if let Some(filter) = override_crypt_filter {
+ crypt_filter = filter;
+ }
+
+ // Compute the key from the original file encryption key and the object identifier to use for
+ // the corresponding object.
+ let key = crypt_filter.compute_key(&state.file_encryption_key, obj_id)?;
+
+ // Decrypt the ciphertext.
+ let plaintext = crypt_filter.decrypt(&key, ciphertext)?;
+
+ // Store the plaintext in the object.
+ match obj {
+ Object::Stream(stream) => stream.set_content(plaintext),
+ Object::String(content, _) => *content = plaintext,
+ _ => (),
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::rc4::Rc4;
+ use crate::creator::tests::create_document;
+ use crate::encryption::{Aes128CryptFilter, Aes256CryptFilter, CryptFilter};
+ use crate::{EncryptionState, EncryptionVersion, Permissions};
+ use rand::RngExt as _;
+ use std::collections::BTreeMap;
+ use std::sync::Arc;
+
+ #[test]
+ fn rc4_works() {
+ let cases = [
+ // Key, Plain, Cipher
+ (
+ String::from("Key"),
+ String::from("Plaintext"),
+ String::from("BBF316E8D940AF0AD3"),
+ ),
+ (String::from("Wiki"), String::from("pedia"), String::from("1021BF0420")),
+ ];
+
+ for (key, plain, cipher) in cases {
+ // Reencode cipher from a hex string to a Vec<u8>
+ let cipher = cipher.as_bytes();
+ let mut cipher_bytes = Vec::with_capacity(cipher.len() / 2);
+ for hex_pair in cipher.as_chunks::<2>().0 {
+ cipher_bytes.push(u8::from_str_radix(std::str::from_utf8(hex_pair).unwrap(), 16).unwrap());
+ }
+
+ let decryptor = Rc4::new(key);
+ let decrypted = decryptor.decrypt(&cipher_bytes);
+ assert_eq!(plain.as_bytes(), &decrypted[..]);
+ }
+ }
+
+ #[test]
+ fn encrypt_v1() {
+ let mut document = create_document();
+
+ let version = EncryptionVersion::V1 {
+ document: &document,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+
+ assert!(document.encrypt(&state).is_ok());
+ assert!(document.decrypt("user").is_ok());
+ }
+
+ #[test]
+ fn encrypt_v2() {
+ let mut document = create_document();
+
+ let version = EncryptionVersion::V2 {
+ document: &document,
+ owner_password: "owner",
+ user_password: "user",
+ key_length: 40,
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+
+ assert!(document.encrypt(&state).is_ok());
+ assert!(document.decrypt("user").is_ok());
+ }
+
+ #[test]
+ fn encrypt_v4() {
+ let mut document = create_document();
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes128CryptFilter);
+
+ let version = EncryptionVersion::V4 {
+ document: &document,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+
+ assert!(document.encrypt(&state).is_ok());
+ assert!(document.decrypt("user").is_ok());
+ }
+
+ #[test]
+ fn decrypt_v4_without_length() {
+ let mut document = create_document();
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes128CryptFilter);
+
+ let version = EncryptionVersion::V4 {
+ document: &document,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+ document.encrypt(&state).unwrap();
+
+ // Length is optional for V4, which fixes the file encryption key at 128
+ // bits, and plenty of producers leave the entry out.
+ let encrypt_id = document.trailer.get(b"Encrypt").unwrap().as_reference().unwrap();
+ document
+ .get_object_mut(encrypt_id)
+ .unwrap()
+ .as_dict_mut()
+ .unwrap()
+ .remove(b"Length");
+
+ assert!(document.decrypt("user").is_ok());
+ }
+
+ #[test]
+ fn encrypt_r5() {
+ let mut document = create_document();
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
+
+ let mut file_encryption_key = [0u8; 32];
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ #[allow(deprecated)]
+ let version = EncryptionVersion::R5 {
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ file_encryption_key: &file_encryption_key,
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+
+ assert!(document.encrypt(&state).is_ok());
+ assert!(document.decrypt("user").is_ok());
+ }
+
+ #[test]
+ fn encrypt_v5() {
+ let mut document = create_document();
+
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
+
+ let mut file_encryption_key = [0u8; 32];
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ let version = EncryptionVersion::V5 {
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ file_encryption_key: &file_encryption_key,
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+
+ let state = EncryptionState::try_from(version).unwrap();
+
+ assert!(document.encrypt(&state).is_ok());
+ assert!(document.decrypt("user").is_ok());
+ }
+}
diff --git a/vendor/lopdf/src/encryption/algorithms.rs b/vendor/lopdf/src/encryption/algorithms.rs
new file mode 100644
index 000000000..db3eb550d
--- /dev/null
+++ b/vendor/lopdf/src/encryption/algorithms.rs
@@ -0,0 +1,1577 @@
+use super::DecryptionError;
+use super::rc4::Rc4;
+use crate::encodings;
+use crate::encryption::Permissions;
+use crate::{Document, Error, Object};
+use aes::cipher::{BlockModeDecrypt as _, BlockModeEncrypt as _, KeyInit as _, KeyIvInit as _};
+use md5::{Digest as _, Md5};
+use rand::RngExt as _;
+use sha2::{Sha256, Sha384, Sha512};
+
+type Aes128CbcEnc = cbc::Encryptor<aes::Aes128>;
+type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
+type Aes256EbcEnc = ecb::Encryptor<aes::Aes256>;
+
+type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
+type Aes256EbcDec = ecb::Decryptor<aes::Aes256>;
+type AesBlock = aes::cipher::Block<aes::Aes128>;
+
+fn aes_block_mut(block: &mut [u8]) -> &mut AesBlock {
+ block.try_into().expect("AES block must be 16 bytes")
+}
+
+// If the password string is less than 32 bytes long, pad it by appending the required number of
+// additional bytes from the beginning of the following padding string.
+const PAD_BYTES: [u8; 32] = [
+ 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, 0x2E, 0x2E, 0x00,
+ 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
+];
+
+#[derive(Clone, Debug, Default)]
+pub struct PasswordAlgorithm {
+ pub(crate) encrypt_metadata: bool,
+ pub(crate) length: Option<usize>,
+ pub(crate) version: i64,
+ pub(crate) revision: i64,
+ pub(crate) owner_value: Vec<u8>,
+ pub(crate) owner_encrypted: Vec<u8>,
+ pub(crate) user_value: Vec<u8>,
+ pub(crate) user_encrypted: Vec<u8>,
+ pub(crate) permissions: Permissions,
+ pub(crate) permission_encrypted: Vec<u8>,
+}
+
+impl TryFrom<&Document> for PasswordAlgorithm {
+ type Error = Error;
+
+ fn try_from(value: &Document) -> Result<Self, Self::Error> {
+ // Get the encrypted dictionary.
+ let encrypted = value
+ .get_encrypted()
+ .map_err(|_| DecryptionError::MissingEncryptDictionary)?;
+
+ // Get the EncryptMetadata field.
+ let encrypt_metadata = encrypted
+ .get(b"EncryptMetadata")
+ .unwrap_or(&Object::Boolean(true))
+ .as_bool()
+ .map_err(|_| DecryptionError::InvalidType)?;
+
+ // Get the Length field if any. Make sure that if it is present that it is a 64-bit integer and
+ // that it can be converted to an unsigned size.
+ let length: Option<usize> = if encrypted.get(b"Length").is_ok() {
+ Some(encrypted.get(b"Length")?.as_i64()?.try_into()?)
+ } else {
+ None
+ };
+
+ // Get the V field.
+ let version = encrypted
+ .get(b"V")
+ .map_err(|_| DecryptionError::MissingVersion)?
+ .as_i64()
+ .map_err(|_| DecryptionError::InvalidType)?;
+
+ // A code specifying the algorithm to be used in encrypting and decrypting the document.
+ match version {
+ // (Deprecated in PDF 2.0) An algorithm that is undocumented. This value shall not be
+ // used.
+ 0 => return Err(DecryptionError::InvalidVersion)?,
+ // (PDF 1.4; deprecated in PDF 2.0) Indicates the use of encryption of data using the
+ // RC4 or AES algorithms with a file encryption key length of 40 bits.
+ 1 => (),
+ // (PDF 1.4; deprecated in PDF 2.0) Indicates the use of encryption of data using the
+ // RC4 or AES algorithms but permitting file encryption key lengths greater or 40 bits.
+ 2 => (),
+ // (PDF 1.4; deprecated in PDF 2.0) An unpublished algorithm that permits encryption
+ // key lengths ranging from 40 to 128 bits. This value shall not appear in a conforming
+ // PDF file.
+ 3 => return Err(DecryptionError::InvalidVersion)?,
+ // (PDF 1.5; deprecated in PDF 2.0) The security handler defines the use of encryption
+ // and decryption in the document, using the rules specified by the CF, StmF and StrF
+ // entries using encryption of data using the RC4 or AES algorithms (deprecated in PDF
+ // 2.0) with a file encryption key length of 128 bits.
+ 4 => (),
+ // (PDF 2.0) The security handler defines the use of encryption and decryption in the
+ // document, using the rules specified by the CF, StmF, StrF and EFF entries using
+ // encryption of data using the AES algorithms with a file encryption key length of 256
+ // bits.
+ 5 => (),
+ // Unknown codes.
+ _ => Err(DecryptionError::UnsupportedVersion)?,
+ }
+
+ // V4 and V5 fix the length of the file encryption key at 128 and 256 bits, so the Length
+ // entry is optional for them and plenty of producers leave it out. Without a default here
+ // the key derivation below falls back to 40 bits and the password check fails on files
+ // that other readers open without complaint.
+ let length = length.or(match version {
+ 4 => Some(128),
+ 5 => Some(256),
+ _ => None,
+ });
+
+ // The length of the file encryption key shall only be present if V is 2 or 3 (but
+ // documents with higher values for V seem to have this field).
+ if let Some(length) = length {
+ match version {
+ // Although "Optional" and/or not required for V1 it appears in some documents
+ // with a default value of 40.
+ 1 => {
+ if length != 40 {
+ Err(DecryptionError::InvalidKeyLength)?;
+ }
+ }
+ // The length of the file encryption key shall be a multiple of 8 in the range 40
+ // to and including 128.
+ 2..=3 => {
+ if length % 8 != 0 || !(40..=128).contains(&length) {
+ Err(DecryptionError::InvalidKeyLength)?;
+ }
+ }
+ // The Length field should not be present if V is 4. However, if it is present it
+ // must be 128.
+ 4 => {
+ if length != 128 {
+ Err(DecryptionError::InvalidKeyLength)?;
+ }
+ }
+ // The Length field should not be present if V is 5. However, if it is present it
+ // must be 256.
+ 5 => {
+ if length != 256 {
+ Err(DecryptionError::InvalidKeyLength)?;
+ }
+ }
+ // The Length field may not be present otherwise.
+ _ => Err(DecryptionError::InvalidKeyLength)?,
+ }
+ }
+
+ // Get the R field.
+ let revision = encrypted
+ .get(b"R")
+ .map_err(|_| DecryptionError::MissingRevision)?
+ .as_i64()
+ .map_err(|_| DecryptionError::InvalidType)?;
+
+ // Get the owner value and owner encrypted blobs.
+ let mut owner_value = encrypted
+ .get(b"O")
+ .map_err(|_| DecryptionError::MissingOwnerPassword)?
+ .as_str()
+ .map_err(|_| DecryptionError::InvalidType)?
+ .to_vec();
+
+ // The owner value is 32 bytes long if the value of R is 4 or less.
+ if revision <= 4 && owner_value.len() != 32 {
+ Err(DecryptionError::InvalidHashLength)?;
+ }
+
+ // The owner value is 48 bytes long if the value of R is 5 or greater.
+ // Some PDF writers pad /O with trailing zeros beyond 48 bytes; truncate
+ // to the spec-required length so these documents are accepted.
+ if revision >= 5 {
+ if owner_value.len() < 48 {
+ Err(DecryptionError::InvalidHashLength)?;
+ }
+ owner_value.truncate(48);
+ }
+
+ let owner_encrypted = encrypted
+ .get(b"OE")
+ .and_then(Object::as_str)
+ .map(|s| s.to_vec())
+ .ok()
+ .unwrap_or_default();
+
+ // The owner encrypted blob is required if R is 5 or greater and the blob shall be 32 bytes
+ // long.
+ if revision >= 5 && owner_encrypted.len() != 32 {
+ Err(DecryptionError::InvalidCipherTextLength)?;
+ }
+
+ // Get the user value and user encrypted blobs.
+ let mut user_value = encrypted
+ .get(b"U")
+ .map_err(|_| DecryptionError::MissingUserPassword)?
+ .as_str()
+ .map_err(|_| DecryptionError::InvalidType)?
+ .to_vec();
+
+ // The user value is 32 bytes long if the value of R is 4 or less.
+ if revision <= 4 && user_value.len() != 32 {
+ Err(DecryptionError::InvalidHashLength)?;
+ }
+
+ // The user value is 48 bytes long if the value of R is 5 or greater.
+ // Some PDF writers pad /U with trailing zeros beyond 48 bytes; truncate
+ // to the spec-required length so these documents are accepted.
+ if revision >= 5 {
+ if user_value.len() < 48 {
+ Err(DecryptionError::InvalidHashLength)?;
+ }
+ user_value.truncate(48);
+ }
+
+ let user_encrypted = encrypted
+ .get(b"UE")
+ .and_then(Object::as_str)
+ .map(|s| s.to_vec())
+ .ok()
+ .unwrap_or_default();
+
+ // The user encrypted blob is required if R is 5 or greater and the blob shall be 32 bytes
+ // long.
+ if revision >= 5 && user_encrypted.len() != 32 {
+ Err(DecryptionError::InvalidCipherTextLength)?;
+ }
+
+ // Get the permission value and permission encrypted blobs.
+ let permission_value = encrypted
+ .get(b"P")
+ .map_err(|_| DecryptionError::MissingPermissions)?
+ .as_i64()
+ .map_err(|_| DecryptionError::InvalidType)? as u64;
+
+ let permissions = Permissions::from_bits_retain(permission_value);
+
+ let permission_encrypted = encrypted
+ .get(b"Perms")
+ .and_then(Object::as_str)
+ .map(|s| s.to_vec())
+ .ok()
+ .unwrap_or_default();
+
+ // The permission encrypted blob is required if R is 65 or greater and the blob shall be
+ // 16 bytes long.
+ if revision >= 5 && permission_encrypted.len() != 16 {
+ Err(DecryptionError::InvalidCipherTextLength)?;
+ }
+
+ Ok(Self {
+ encrypt_metadata,
+ length,
+ version,
+ revision,
+ owner_value,
+ owner_encrypted,
+ user_value,
+ user_encrypted,
+ permissions,
+ permission_encrypted,
+ })
+ }
+}
+
+impl PasswordAlgorithm {
+ /// Sanitize the password (revision 4 and earlier).
+ ///
+ /// This implements the first step of Algorithm 2 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ pub(crate) fn sanitize_password_r4(&self, password: &str) -> Result<Vec<u8>, DecryptionError> {
+ // The password string is generated from host system codepage characters (or system scripts) by
+ // first converting the string to PDFDocEncoding. If the input is Unicode, first convert to a
+ // codepage encoding, and then to PDFDocEncoding for backward compatibility.
+ let password = encodings::string_to_bytes(&encodings::PDF_DOC_ENCODING, password);
+
+ Ok(password)
+ }
+
+ /// Compute a file encryption key in order to encrypt/decrypt a document (revision 4 and
+ /// earlier).
+ ///
+ /// This implements Algorithm 2 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ pub(crate) fn compute_file_encryption_key_r4<P>(
+ &self, doc: &Document, password: P,
+ ) -> Result<Vec<u8>, DecryptionError>
+ where
+ P: AsRef<[u8]>,
+ {
+ let password = password.as_ref();
+
+ // Pad or truncate the resulting password string to exactly 32 bytes. If the password string is
+ // more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad
+ // it by appending the required number of additional bytes from the beginning of the following
+ // padding string (see `PAD_BYTES`).
+ //
+ // That is, if the password is n bytes long, append the first 32 - n bytes of the padding
+ // string to the end of the password string. If the password string is empty (zero-length),
+ // meaning there is no user password, substitute the entire padding string in its place.
+ //
+ // i.e., we will simply calculate `len = min(password length, 32)` and use the first len bytes
+ // of password and the first len bytes of `PAD_BYTES`.
+ let len = password.len().min(32);
+
+ // Initialize the MD5 hash function and pass the result as input to this function.
+ let mut hasher = Md5::new();
+
+ hasher.update(&password[..len]);
+ hasher.update(&PAD_BYTES[..32 - len]);
+
+ // Pass the value of the encryption dictionary's O entry (owner password hash) to the MD5 hash
+ // function.
+ hasher.update(&self.owner_value);
+
+ // Convert the integer value of the P entry (permissions) to a 32-bit unsigned binary number
+ // and pass these bytes to the MD5 hash function, low-order byte first.
+ //
+ // We don't actually care about the permissions, but we need the correct value to derive the
+ // correct key.
+ hasher.update((self.permissions.bits() as u32).to_le_bytes());
+
+ // Pass the first element of the file's file identifier array (the value of the ID entry in the
+ // document's trailer dictionary to the MD5 hash function.
+ let file_id_0 = doc
+ .trailer
+ .get(b"ID")
+ .map_err(|_| DecryptionError::MissingFileID)?
+ .as_array()
+ .map_err(|_| DecryptionError::InvalidType)?
+ .first()
+ .ok_or(DecryptionError::InvalidType)?
+ .as_str()
+ .map_err(|_| DecryptionError::InvalidType)?;
+ hasher.update(file_id_0);
+
+ // (Security handlers of revision 4 or greater) If document metadata is not being encrypted,
+ // pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
+ if self.revision >= 4 && !self.encrypt_metadata {
+ hasher.update(b"\xff\xff\xff\xff");
+ }
+
+ // Finish the hash.
+ let mut hash = hasher.finalize();
+
+ // (Security handlers of revision 3 or greater) Do the following 50 times: take the output from
+ // the previous MD5 hash and pass the first n bytes of the output as input into a new MD5 hash,
+ // where n is the number of bytes of the file encryption key as defined by the value of the
+ // encryption dictionary's Length entry.
+ let n = if self.revision >= 3 {
+ self.length.unwrap_or(40) / 8
+ } else {
+ 5
+ };
+
+ // The maximum supported key length is 16 bytes (128 bits) due to the use of MD5.
+ if n > 16 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+
+ if self.revision >= 3 {
+ for _ in 0..50 {
+ hash = Md5::digest(&hash[..n]);
+ }
+ }
+
+ // Set the file encryption key to the first n bytes of the output from the final MD5 hash,
+ // where n shall always be 5 for security handlers of revision 2 but, for security handlers of
+ // revision 3 or greater, shall depend on the value of the encrpytion dictionary's Length
+ // entry.
+ Ok(hash[..n].to_vec())
+ }
+
+ /// Sanitize the password (revision 6 and later).
+ ///
+ /// This implements the first step of Algorithm 2.A as described in ISO 32000-2:2020 (PDF 2.0).
+ pub(crate) fn sanitize_password_r6(&self, password: &str) -> Result<Vec<u8>, DecryptionError> {
+ // The UTF-8 password string shall be generated from Unicode input by processing the input
+ // with the SASLprep (Internet RFC 4013) profile of stringprep (Internet RFC 3454) using
+ // the Normalize and BiDi options, and then coverting to a UTF-8 representation.
+ Ok(stringprep::saslprep(password)?.as_bytes().to_vec())
+ }
+
+ /// Compute a file encryption key in order to encrypt/decrypt a document (revision 6 and
+ /// later).
+ ///
+ /// This implements Algorithm 2.A as described in ISO 32000-2:2020 (PDF 2.0).
+ fn compute_file_encryption_key_r6<P>(&self, password: P) -> Result<Vec<u8>, DecryptionError>
+ where
+ P: AsRef<[u8]>,
+ {
+ let mut password = password.as_ref();
+
+ let hashed_owner_password = &self.owner_value[0..][..32];
+ let owner_validation_salt = &self.owner_value[32..][..8];
+ let owner_key_salt = &self.owner_value[40..][..8];
+
+ let hashed_user_password = &self.user_value[0..][..32];
+ let user_validation_salt = &self.user_value[32..][..8];
+ let user_key_salt = &self.user_value[40..][..8];
+
+ // Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
+ if password.len() > 127 {
+ password = &password[..127];
+ }
+
+ // Test the password against the owner key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 password concatenated with the 8 bytes of owner
+ // validation salt, concatenated with the 48-byte U string. If the 32-byte result matches
+ // the first 32 bytes of the O string, this is the owner password.
+ if self.compute_hash(password, owner_validation_salt, Some(&self.user_value))? == hashed_owner_password {
+ // Compute an intermediate owner key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 owner password concatenated with the 8 bytes of
+ // owner key salt, concatenated with the 48-byte U string.
+ let hash = self.compute_hash(password, owner_key_salt, Some(&self.user_value))?;
+
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&hash);
+
+ // The 32-byte result is the key used to decrypt the 32-byte OE string using AES-256 in
+ // CBC mode with no padding and an initialization vector of zero. The 32-byte result is
+ // the file encryption key.
+ let iv = [0u8; 16];
+
+ let mut owner_encrypted = self.owner_encrypted.clone();
+ let mut decryptor = Aes256CbcDec::new(&key.into(), &iv.into());
+
+ for block in owner_encrypted.as_chunks_mut::<16>().0 {
+ decryptor.decrypt_block(aes_block_mut(block));
+ }
+
+ return Ok(owner_encrypted);
+ }
+
+ // Note: this step is not in the specification, but is a precaution.
+ //
+ // Test the password against the user key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 password concatenated with the 8 bytes of user
+ // validation salt. If the 32-byte result matches the first 32-bytes of the U string, this
+ // is the user password.
+
+ if self.compute_hash(password, user_validation_salt, None)? == hashed_user_password {
+ // Compute an intermediate user key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 owner password concatenated with the 8 bytes of
+ // user key salt.
+ let hash = self.compute_hash(password, user_key_salt, None)?;
+
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&hash);
+
+ // The 32-byte result is the key used to decrypt the 32-byte UE string using AES-256 in
+ // CBC mode with no padding and an initialization vector of zero. The 32-byte result is
+ // the file encryption key.
+ let iv = [0u8; 16];
+ let mut user_encrypted = self.user_encrypted.clone();
+ let mut decryptor = Aes256CbcDec::new(&key.into(), &iv.into());
+
+ for block in user_encrypted.as_chunks_mut::<16>().0 {
+ decryptor.decrypt_block(aes_block_mut(block));
+ }
+
+ // Decrypt the 16-byte Perms string using AES-256 in EBC mode with an initialization
+ // vector of zero and the file encryption key as the key. Verify that bytes 9-11 of the
+ // result are the characters "a", "d", "b". Bytes 0-3 of the decrypted Perms entry,
+ // treated as a little-endian integer, are the user permissions. They shall match the
+ // value in the P key.
+ //
+ // i.e., use algorithm 13 to validate the permissions.
+ self.validate_permissions(&user_encrypted)?;
+
+ return Ok(user_encrypted);
+ }
+
+ Err(DecryptionError::IncorrectPassword)
+ }
+
+ /// Compute a hash (revision 6 and later).
+ ///
+ /// This implements Algorithm 2.B as described in ISO 32000-2:2020 (PDF 2.0).
+ fn compute_hash<P, S>(&self, password: P, salt: S, user_key: Option<&[u8]>) -> Result<Vec<u8>, DecryptionError>
+ where
+ P: AsRef<[u8]>,
+ S: AsRef<[u8]>,
+ {
+ let password = password.as_ref();
+ let salt = salt.as_ref();
+
+ // Take the SHA-256 hash of the original input to the algorithm and name the resulting 32
+ // bytes, K.
+ let mut hasher = Sha256::new();
+
+ hasher.update(password);
+ hasher.update(salt);
+
+ if let Some(user_key) = user_key {
+ hasher.update(user_key);
+ }
+
+ let mut k = hasher.finalize().to_vec();
+
+ // Revision 5 uses a simplified hash algorithm that simply calculates the SHA-256 hash of
+ // the original input to the algorithm.
+ if self.revision == 5 {
+ return Ok(k);
+ }
+
+ let mut k1 =
+ Vec::with_capacity(64 * (password.len() + 64 + user_key.map(|user_key| user_key.len()).unwrap_or(0)));
+
+ // Perform the following steps at least 64 times, until the value of the last byte in K is
+ // less than or equal to (round number) - 32.
+ for round in 1.. {
+ // Make a new string K0 as follows:
+ //
+ // * When checking the owner password or creating the owner key, K0 is the concatenation of the input
+ // password, K, and the 48-byte user key.
+ // * Otherwise, K0 is the concatenation of the input password and K.
+ //
+ // Next, set K1 to 64 repetitions of K0.
+ k1.clear();
+
+ for _ in 0..64 {
+ k1.extend_from_slice(password);
+ k1.extend_from_slice(&k);
+
+ if let Some(user_key) = user_key {
+ k1.extend_from_slice(user_key);
+ }
+ }
+
+ // Encrypt K1 with the AES-128 (CBC, no padding) algorithm, using the first 16 bytes of
+ // K as the key, and the second 16 bytes of K as the initialization vector. The result
+ // of this encryption is E.
+ //
+ // The 64 repetitions of K0 ensure that K1 is a multiple of 64 bytes, thus a multiple
+ // of 16 bytes, i.e., it does not require padding.
+ let key: &[u8; 16] = k[..16].try_into().expect("hash key must be 16 bytes");
+ let iv: &[u8; 16] = k[16..32].try_into().expect("hash IV must be 16 bytes");
+
+ let mut encryptor = Aes128CbcEnc::new(key.into(), iv.into());
+
+ for block in k1.as_chunks_mut::<16>().0 {
+ encryptor.encrypt_block(aes_block_mut(block));
+ }
+
+ let e = k1;
+
+ // Taking the first 16 bytes of E as an unsigned big-endian integer, compute the
+ // remainder, modulo 3. If the result is 0, the next hash used is SHA-256. If the
+ // result is 1, the next hash used is SHA-384. If the result is 2, the next hash used
+ // is SHA-256.
+ //
+ // Using the hash algorithm determined in the previous step, take the hash of E. The
+ // result is a new value of K, which will be 32, 48 or 64 bytes in length.
+ k = match e[..16].iter().map(|v| *v as u32).sum::<u32>() % 3 {
+ 0 => Sha256::digest(&e).to_vec(),
+ 1 => Sha384::digest(&e).to_vec(),
+ 2 => Sha512::digest(&e).to_vec(),
+ _ => unreachable!(),
+ };
+
+ // Look at the very last byte of E. If the value of that byte (taken as an unsigned
+ // integer) is greater than the round number - 32, repeat the round again.
+ //
+ // Repeat rounds until the value of the last byte is less than or equal to (round
+ // number) - 32.
+ if round >= 64 && e.last().copied().unwrap_or(0) as u32 <= round - 32 {
+ break;
+ }
+
+ // Move e into k1 for the next round (to reuse k1).
+ k1 = e;
+ }
+
+ // The first 32 bytes of the final K are the output of the algorithm.
+ k.truncate(32);
+
+ Ok(k)
+ }
+
+ /// Compute the encryption dictionary's O-entry value (revision 4 and earlier).
+ ///
+ /// This implements Algorithm 3 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ pub(crate) fn compute_hashed_owner_password_r4<O, U>(
+ &self, owner_password: Option<O>, user_password: U,
+ ) -> Result<Vec<u8>, DecryptionError>
+ where
+ O: AsRef<[u8]>,
+ U: AsRef<[u8]>,
+ {
+ let user_password = user_password.as_ref();
+
+ // Pad or truncate the owner string. If there is no owner password, use the user password
+ // instead.
+ let password = owner_password
+ .as_ref()
+ .map(|password| password.as_ref())
+ .unwrap_or(user_password);
+
+ // Pad or truncate the resulting password string to exactly 32 bytes. If the password string is
+ // more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad
+ // it by appending the required number of additional bytes from the beginning of the following
+ // padding string (see `PAD_BYTES`).
+ //
+ // That is, if the password is n bytes long, append the first 32 - n bytes of the padding
+ // string to the end of the password string. If the password string is empty (zero-length),
+ // meaning there is no user password, substitute the entire padding string in its place.
+ //
+ // i.e., we will simply calculate `len = min(password length, 32)` and use the first len bytes
+ // of password and the first len bytes of `PAD_BYTES`.
+ let len = password.len().min(32);
+
+ // Initialize the MD5 hash function and pass the result as input to this function.
+ let mut hasher = Md5::new();
+
+ hasher.update(&password[..len]);
+ hasher.update(&PAD_BYTES[..32 - len]);
+
+ let mut hash = hasher.finalize();
+
+ // (Security handlers of revision 3 or greater) Do the following 50 times: take the output from
+ // the previous MD5 hash and pass it as input into a new MD5 hash.
+ if self.revision >= 3 {
+ for _ in 0..50 {
+ hash = Md5::digest(hash);
+ }
+ }
+
+ // Create an RC4 file encryption key using the first n bytes of the output from the final MD5
+ // hash, where n shall always be 5 for security handlers of revision 2 but, for security
+ // handlers of revision 3 or greater, shall depend on the value of the encryption dictionary's
+ // Length entry.
+ let n = if self.revision >= 3 {
+ self.length.unwrap_or(40) / 8
+ } else {
+ 5
+ };
+
+ // The maximum supported key length is 16 bytes (128 bits) due to the use of MD5.
+ if n > 16 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+
+ // Pad or truncate the user password string to exactly 32 bytes. If the user password string is
+ // more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad
+ // it by appending the required number of additional bytes from the beginning of the following
+ // padding string (see `PAD_BYTES`).
+ //
+ // That is, if the password is n bytes long, append the first 32 - n bytes of the padding
+ // string to the end of the password string. If the password string is empty (zero-length),
+ // meaning there is no user password, substitute the entire padding string in its place.
+ //
+ // i.e., we will simply calculate `len = min(password length, 32)` and use the first len bytes
+ // of password and the first len bytes of `PAD_BYTES`.
+ let len = user_password.len().min(32);
+
+ // Encrypt the result of the previous step using an RC4 encryption function with the RC4 file
+ // encryption key obtained in the step before the previous step.
+ let mut bytes = [0u8; 32];
+
+ bytes[..len].copy_from_slice(&user_password[..len]);
+ bytes[len..].copy_from_slice(&PAD_BYTES[..32 - len]);
+
+ let mut result = Rc4::new(&hash[..n]).encrypt(bytes);
+
+ // (Security handlers of revision 3 or greater) Do the following 19 times: Take the output from
+ // the previous invocation of the RC4 function and pass it as input to a new invocation of the
+ // function; use a file encryption key generated by taking each byte of the RC4 file encryption
+ // key and performing an XOR (exclusive or) operation between that byte and the single-byte
+ // value of the iteration counter (from 1 to 19).
+ if self.revision >= 3 {
+ let mut key = vec![0u8; n];
+
+ for i in 1..=19 {
+ for (in_byte, out_byte) in hash[..n].iter().zip(key.iter_mut()) {
+ *out_byte = in_byte ^ i;
+ }
+
+ result = Rc4::new(&key).encrypt(&result);
+ }
+ }
+
+ // Store the output from the final invocation of the RC4 function as the value of the O entry
+ // in the encryption dictionary.
+ Ok(result)
+ }
+
+ /// Compute the encryption dictionary's U-entry value (revision 2).
+ ///
+ /// This implements Algorithm 4 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ pub(crate) fn compute_hashed_user_password_r2<U>(
+ &self, doc: &Document, user_password: U,
+ ) -> Result<Vec<u8>, DecryptionError>
+ where
+ U: AsRef<[u8]>,
+ {
+ // Create a file encryption key based on the user password string.
+ let file_encryption_key = self.compute_file_encryption_key_r4(doc, user_password)?;
+
+ // Encrypt the 32-byte padding string using an RC4 encryption function with the file encryption
+ // key from the preceding step.
+ let result = Rc4::new(&file_encryption_key).encrypt(PAD_BYTES);
+
+ // Store the result of the previous step as the value of the U entry in the encryption dictionary.
+ Ok(result)
+ }
+
+ /// Compute the encryption dictionary's U-entry value (revision 3 or 4).
+ ///
+ /// This implements Algorithm 5 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ pub(crate) fn compute_hashed_user_password_r3_r4<U>(
+ &self, doc: &Document, user_password: U,
+ ) -> Result<Vec<u8>, DecryptionError>
+ where
+ U: AsRef<[u8]>,
+ {
+ // Create a file encryption key based on the user password string.
+ let file_encryption_key = self.compute_file_encryption_key_r4(doc, user_password)?;
+
+ // Initialize the MD5 hash function and pass the 32-byte padding string.
+ let mut hasher = Md5::new();
+
+ hasher.update(PAD_BYTES);
+
+ // Pass the first element of the file's file identifier array (the value of the ID entry in the
+ // document's trailer dictionary) to the hash function and finish the hash.
+ let file_id_0 = doc
+ .trailer
+ .get(b"ID")
+ .map_err(|_| DecryptionError::MissingFileID)?
+ .as_array()
+ .map_err(|_| DecryptionError::InvalidType)?
+ .first()
+ .ok_or(DecryptionError::InvalidType)?
+ .as_str()
+ .map_err(|_| DecryptionError::InvalidType)?;
+ hasher.update(file_id_0);
+
+ let hash = hasher.finalize();
+
+ // Encrypt the 16-byte result of the hash, using an RC4 encryption function with the file
+ // encryption key.
+ let mut result = Rc4::new(&file_encryption_key).encrypt(hash);
+
+ // Do the following 19 times: Take the output from the previous invocation of the RC4 function
+ // and pass it as input to a new invocation of the function; use a file encryption key
+ // generated by taking each byte of the RC4 file encryption key and performing an XOR
+ // (exclusive or) operation between that byte and the single-byte value of the iteration
+ // counter (from 1 to 19).
+ let mut key = vec![0u8; file_encryption_key.len()];
+
+ for i in 1..=19 {
+ for (in_byte, out_byte) in file_encryption_key.iter().zip(key.iter_mut()) {
+ *out_byte = in_byte ^ i;
+ }
+
+ result = Rc4::new(&key).encrypt(&result);
+ }
+
+ // Append 16 bytes of arbitrary padding to the output from the final invocation of the RC4
+ // function and store the 32-byte result as the value of the U entry in the encryption
+ // dictionary.
+ result.resize(32, 0);
+
+ let mut rng = rand::rng();
+ rng.fill(&mut result[16..]);
+
+ Ok(result)
+ }
+
+ /// Authenticate the user password (revision 4 and earlier).
+ ///
+ /// This implements Algorithm 6 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ fn authenticate_user_password_r4<U>(&self, doc: &Document, user_password: U) -> Result<(), DecryptionError>
+ where
+ U: AsRef<[u8]>,
+ {
+ // Perform all but the last step of Algorithm 4 (security handlers of revision 2) or Algorithm
+ // 5 (security handlers of revision 3 or 4) using the supplied password string to compute the
+ // encryption dictionary's U-entry value.
+ let hashed_user_password = match self.revision {
+ 2 => self.compute_hashed_user_password_r2(doc, &user_password)?,
+ 3 | 4 => self.compute_hashed_user_password_r3_r4(doc, &user_password)?,
+ _ => return Err(DecryptionError::InvalidRevision),
+ };
+
+ // If the result of the previous step is equal to the value of the encryption dictionary's U
+ // entry (comparing on the first 16 bytes in the case of security handlers of revision 3 or
+ // greater), the password supplied is the correct user password.
+ let len = match self.revision {
+ 3 | 4 => 16,
+ _ => hashed_user_password.len(),
+ };
+
+ if self.user_value.len() < len {
+ return Err(DecryptionError::InvalidHashLength);
+ }
+
+ if hashed_user_password[..len] != self.user_value[..len] {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ Ok(())
+ }
+
+ /// Authenticate the owner password (revision 4 and earlier).
+ ///
+ /// This implements Algorithm 7 as described in ISO 32000-2:2020 (PDF 2.0).
+ ///
+ /// This algorithm is deprecated in PDF 2.0.
+ fn authenticate_owner_password_r4<O>(&self, doc: &Document, owner_password: O) -> Result<(), DecryptionError>
+ where
+ O: AsRef<[u8]>,
+ {
+ // Pad or truncate the owner string. If there is no owner password, use the user password
+ // instead.
+ let password = owner_password.as_ref();
+
+ // Pad or truncate the resulting password string to exactly 32 bytes. If the password string is
+ // more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad
+ // it by appending the required number of additional bytes from the beginning of the following
+ // padding string (see `PAD_BYTES`).
+ //
+ // That is, if the password is n bytes long, append the first 32 - n bytes of the padding
+ // string to the end of the password string. If the password string is empty (zero-length),
+ // meaning there is no user password, substitute the entire padding string in its place.
+ //
+ // i.e., we will simply calculate `len = min(password length, 32)` and use the first len bytes
+ // of password and the first len bytes of `PAD_BYTES`.
+ let len = password.len().min(32);
+
+ // Initialize the MD5 hash function and pass the result as input to this function.
+ let mut hasher = Md5::new();
+
+ hasher.update(&password[..len]);
+ hasher.update(&PAD_BYTES[..32 - len]);
+
+ let mut hash = hasher.finalize();
+
+ // (Security handlers of revision 3 or greater) Do the following 50 times: take the output from
+ // the previous MD5 hash and pass it as input into a new MD5 hash.
+ if self.revision >= 3 {
+ for _ in 0..50 {
+ hash = Md5::digest(hash);
+ }
+ }
+
+ // Create an RC4 file encryption key using the first n bytes of the output from the final MD5
+ // hash, where n shall always be 5 for security handlers of revision 2 but, for security
+ // handlers of revision 3 or greater, shall depend on the value of the encryption dictionary's
+ // Length entry.
+ let n = if self.revision >= 3 {
+ self.length.unwrap_or(40) / 8
+ } else {
+ 5
+ };
+
+ // The maximum supported key length is 16 bytes (128 bits) due to the use of MD5.
+ if n > 16 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+
+ // Decrypt the value of the encryption dictionary's O entry, using an RC4 encryption function
+ // with the file encryption key to retrieve the user password.
+ let mut result = self.owner_value.to_vec();
+
+ // (Security handlers of revision 3 or greater) Do the following 19 times: Take the output from
+ // the previous invocation of the RC4 function and pass it as input to a new invocation of the
+ // function; use a file encryption key generated by taking each byte of the RC4 file encryption
+ // key and performing an XOR (exclusive or) operation between that byte and the single-byte
+ // value of the iteration counter (from 19 to 1).
+ if self.revision >= 3 {
+ let mut key = vec![0u8; n];
+
+ for i in (1..=19).rev() {
+ for (in_byte, out_byte) in hash[..n].iter().zip(key.iter_mut()) {
+ *out_byte = in_byte ^ i;
+ }
+
+ result = Rc4::new(&key).decrypt(&result);
+ }
+ }
+
+ // (Security handler of revision 2 and the final step for revision 3 or greater) Decrypt the
+ // value of the encryption dictionary's O entry, using an RC4 encryption function with the file
+ // encryption key.
+ result = Rc4::new(&hash[..n]).decrypt(&result);
+
+ // The result of the previous step purports to be the user password. Authenticate this user
+ // password using Algorithm 5. If it is correct, the password supplied is the correct owner
+ // password.
+ self.authenticate_user_password_r4(doc, &result)
+ }
+
+ /// Compute the encryption dictionary's U-entry value (revision 6).
+ ///
+ /// This implements Algorithm 8 as described in ISO 32000-2:2020 (PDF 2.0).
+ pub(crate) fn compute_hashed_user_password_r6<K, U>(
+ &self, file_encryption_key: K, user_password: U,
+ ) -> Result<(Vec<u8>, Vec<u8>), DecryptionError>
+ where
+ K: AsRef<[u8]>,
+ U: AsRef<[u8]>,
+ {
+ let file_encryption_key = file_encryption_key.as_ref();
+ let user_password = user_password.as_ref();
+
+ // Generate 16 random bytes of data using a strong random number generator. The first 8
+ // bytes are the user validation salt. The second 8 bytes are the user key salt. Compute
+ // the 32-byte hash using algorithm 2.B with an input string consisting of the UTF-8
+ // password concatenated with the user validation salt. The 48-byte string consisting of
+ // the 32-byte hash followed by the user validation salt followed by the user key salt is
+ // stored as the U key.
+ let mut user_value = [0u8; 48];
+ let mut rng = rand::rng();
+
+ rng.fill(&mut user_value[32..]);
+
+ let user_validation_salt = &user_value[32..][..8];
+
+ let mut input = Vec::with_capacity(user_password.len() + user_validation_salt.len());
+
+ input.extend_from_slice(user_password);
+ input.extend_from_slice(user_validation_salt);
+
+ let hashed_user_password = self.compute_hash(user_password, user_validation_salt, None)?;
+ user_value[..32].copy_from_slice(&hashed_user_password);
+
+ // Compute the 32-byte hash using algorithm 2.B with an input string consisting of the
+ // UTF-8 password concatenated with the user key salt.
+ let user_key_salt = &user_value[40..][..8];
+
+ input.clear();
+
+ input.extend_from_slice(user_password);
+ input.extend_from_slice(user_key_salt);
+
+ let hash = self.compute_hash(user_password, user_key_salt, None)?;
+
+ // Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode
+ // with no padding and initialization vector of zero. The resulting 32-byte string is
+ // stored as the UE key.
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&hash);
+
+ let iv = [0u8; 16];
+
+ let mut user_encrypted = file_encryption_key.to_vec();
+ let mut encryptor = Aes256CbcEnc::new(&key.into(), &iv.into());
+
+ for block in user_encrypted.as_chunks_mut::<16>().0 {
+ encryptor.encrypt_block(aes_block_mut(block));
+ }
+
+ Ok((user_value.to_vec(), user_encrypted))
+ }
+
+ /// Compute the encryption dictionary's O-entry value (revision 6).
+ ///
+ /// This implements Algorithm 9 as described in ISO 32000-2:2020 (PDF 2.0).
+ pub(crate) fn compute_hashed_owner_password_r6<K, O>(
+ &self, file_encryption_key: K, owner_password: O,
+ ) -> Result<(Vec<u8>, Vec<u8>), DecryptionError>
+ where
+ K: AsRef<[u8]>,
+ O: AsRef<[u8]>,
+ {
+ let file_encryption_key = file_encryption_key.as_ref();
+ let owner_password = owner_password.as_ref();
+
+ // Generate 16 random bytes of data using a strong random number generator. The first 8
+ // bytes are the owner validation salt. The second 8 bytes are the owner key salt. Compute
+ // the 32-byte hash using algorithm 2.B with an input string consisting of the UTF-8
+ // password concatenated with the owner validation salt and then concatenated with the
+ // 48-byte U string as generated in Algorithm 8. The 48-byte string consisting of the
+ // 32-byte hash followed by the owner validation salt followed by the owner key salt is
+ // stored as the O key.
+ let mut owner_value = [0u8; 48];
+ let mut rng = rand::rng();
+
+ rng.fill(&mut owner_value[32..]);
+
+ let owner_validation_salt = &owner_value[32..][..8];
+
+ let hashed_owner_password = self.compute_hash(owner_password, owner_validation_salt, Some(&self.user_value))?;
+ owner_value[..32].copy_from_slice(&hashed_owner_password);
+
+ // Compute the 32-byte hash using algorithm 2.B with an input string consisting of the
+ // UTF-8 password concatenated with the owner key salt.
+ let owner_key_salt = &owner_value[40..][..8];
+
+ let hash = self.compute_hash(owner_password, owner_key_salt, Some(&self.user_value))?;
+
+ // Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode
+ // with no padding and initialization vector of zero. The resulting 32-byte string is
+ // stored as the OE key.
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&hash);
+
+ let iv = [0u8; 16];
+
+ let mut owner_encrypted = file_encryption_key.to_vec();
+ let mut encryptor = Aes256CbcEnc::new(&key.into(), &iv.into());
+
+ for block in owner_encrypted.as_chunks_mut::<16>().0 {
+ encryptor.encrypt_block(aes_block_mut(block));
+ }
+
+ Ok((owner_value.to_vec(), owner_encrypted))
+ }
+
+ /// Compute the encryption dictionary's Perms (permissions) value (revision 6 and later).
+ ///
+ /// This implements Algorithm 10 as described in ISO 32000-2:2020 (PDF 2.0).
+ pub(crate) fn compute_permissions<K>(&self, file_encryption_key: K) -> Result<Vec<u8>, DecryptionError>
+ where
+ K: AsRef<[u8]>,
+ {
+ let file_encryption_key = file_encryption_key.as_ref();
+ let mut bytes = [0u8; 16];
+
+ // Record the 8 bytes of permission in the bytes 0-7 of the block, low order byte first.
+ bytes[..8].copy_from_slice(&u64::to_le_bytes(self.permissions.bits()));
+
+ // Set byte 8 to ASCII character "T" or "F" according to the EncryptMetadata boolean.
+ bytes[8] = if self.encrypt_metadata { b'T' } else { b'F' };
+
+ // Set bytes 9-11 to the ASCII characters "a", "d", "b".
+ bytes[9..][..3].copy_from_slice(b"adb");
+
+ // Set bytes 12-15 to 4 bytes of random data, which will be ignored.
+ let mut rng = rand::rng();
+ rng.fill(&mut bytes[12..][..4]);
+
+ // Encrypt the 16-byte block using AES-256 in ECB mode with an initialization vector of
+ // zero, using the file encryption key as the key.
+ let mut key = [0u8; 32];
+ key.copy_from_slice(file_encryption_key);
+
+ let mut encryptor = Aes256EbcEnc::new(&key.into());
+
+ for block in bytes.as_chunks_mut::<16>().0 {
+ encryptor.encrypt_block(aes_block_mut(block));
+ }
+
+ // The result (16 bytes) is stored as the Perms string, and checked for validity when the
+ // file is opened.
+ Ok(bytes.to_vec())
+ }
+
+ /// Authenticate the user password (revision 6 and later).
+ ///
+ /// This implements Algorithm 11 as described in ISO 32000-2:2020 (PDF 2.0).
+ fn authenticate_user_password_r6<U>(&self, user_password: U) -> Result<(), DecryptionError>
+ where
+ U: AsRef<[u8]>,
+ {
+ let mut user_password = user_password.as_ref();
+
+ let hashed_user_password = &self.user_value[0..][..32];
+ let user_validation_salt = &self.user_value[32..][..8];
+
+ // Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
+ if user_password.len() > 127 {
+ user_password = &user_password[..127];
+ }
+
+ // Test the password against the user key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 password concatenated with the 8 bytes of user
+ // validation salt. If the 32-byte result matches the first 32-bytes of the U string, this
+ // is the user password.
+ let mut input = Vec::with_capacity(user_password.len() + user_validation_salt.len());
+
+ input.extend_from_slice(user_password);
+ input.extend_from_slice(user_validation_salt);
+
+ if self.compute_hash(user_password, user_validation_salt, None)? != hashed_user_password {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ Ok(())
+ }
+
+ /// Authenticate the owner password (revision 6 and later).
+ ///
+ /// This implements Algorithm 12 as described in ISO 32000-2:2020 (PDF 2.0).
+ fn authenticate_owner_password_r6<O>(&self, owner_password: O) -> Result<(), DecryptionError>
+ where
+ O: AsRef<[u8]>,
+ {
+ let mut owner_password = owner_password.as_ref();
+
+ let hashed_owner_password = &self.owner_value[0..][..32];
+ let owner_validation_salt = &self.owner_value[32..][..8];
+
+ // Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
+ if owner_password.len() > 127 {
+ owner_password = &owner_password[..127];
+ }
+
+ // Test the password against the owner key by computing a hash using algorithm 2.B with an
+ // input string consisting of the UTF-8 password concatenated with the 8 bytes of owner
+ // validation salt and the 48 byte U string. If the 32-byte result matches the first
+ // 32-bytes of the O string, this is the owner password.
+ let mut input = Vec::with_capacity(owner_password.len() + owner_validation_salt.len());
+
+ input.extend_from_slice(owner_password);
+ input.extend_from_slice(owner_validation_salt);
+
+ if self.compute_hash(owner_password, owner_validation_salt, Some(&self.user_value))? != hashed_owner_password {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ Ok(())
+ }
+
+ /// Validate the permissions (revision 6 and later).
+ ///
+ /// This implements Algorithm 13 as described in ISO 32000-2:2020 (PDF 2.0).
+ fn validate_permissions<K>(&self, file_encryption_key: K) -> Result<(), DecryptionError>
+ where
+ K: AsRef<[u8]>,
+ {
+ let file_encryption_key = file_encryption_key.as_ref();
+
+ // Decrypt the 16 byte Perms string using AES-256 in ECB mode with an initialization vector
+ // of zero and the file encryption key as the key.
+ let mut bytes = [0u8; 16];
+ bytes.copy_from_slice(&self.permission_encrypted);
+
+ let mut key = [0u8; 32];
+ key.copy_from_slice(file_encryption_key);
+
+ let mut decryptor = Aes256EbcDec::new(&key.into());
+
+ for block in bytes.as_chunks_mut::<16>().0 {
+ decryptor.decrypt_block(aes_block_mut(block));
+ }
+
+ // Verify that bytes 9-11 of the result are the characters "a", "d", "b".
+ if &bytes[9..][..3] != b"adb" {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ // Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer, are the
+ // user permissions. They should match the value in the P key.
+ if bytes[..3] != u64::to_le_bytes(self.permissions.bits())[..3] {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ // Byte 8 should match the ASCII character "T" or "F" according to the boolean value of the
+ // EncryptMetadata key.
+ if bytes[8] != if self.encrypt_metadata { b'T' } else { b'F' } {
+ return Err(DecryptionError::IncorrectPassword);
+ }
+
+ Ok(())
+ }
+
+ /// Sanitize the password.
+ pub fn sanitize_password(&self, password: &str) -> Result<Vec<u8>, DecryptionError> {
+ match self.revision {
+ 2..=4 => self.sanitize_password_r4(password),
+ 5..=6 => self.sanitize_password_r6(password),
+ _ => Err(DecryptionError::UnsupportedRevision),
+ }
+ }
+
+ /// Compute the file encryption key used to encrypt/decrypt the document.
+ pub fn compute_file_encryption_key<P>(&self, doc: &Document, password: P) -> Result<Vec<u8>, DecryptionError>
+ where
+ P: AsRef<[u8]>,
+ {
+ match self.revision {
+ 2..=4 => self.compute_file_encryption_key_r4(doc, password),
+ 5..=6 => self.compute_file_encryption_key_r6(password),
+ _ => Err(DecryptionError::UnsupportedRevision),
+ }
+ }
+
+ /// Authenticate the owner password.
+ pub fn authenticate_user_password<U>(&self, doc: &Document, user_password: U) -> Result<(), DecryptionError>
+ where
+ U: AsRef<[u8]>,
+ {
+ match self.revision {
+ 2..=4 => self.authenticate_user_password_r4(doc, user_password),
+ 5..=6 => self.authenticate_user_password_r6(user_password),
+ _ => Err(DecryptionError::UnsupportedRevision),
+ }
+ }
+
+ /// Authenticate the owner password.
+ pub fn authenticate_owner_password<O>(&self, doc: &Document, owner_password: O) -> Result<(), DecryptionError>
+ where
+ O: AsRef<[u8]>,
+ {
+ match self.revision {
+ 2..=4 => self.authenticate_owner_password_r4(doc, owner_password),
+ 5..=6 => self.authenticate_owner_password_r6(owner_password),
+ _ => Err(DecryptionError::UnsupportedRevision),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::Permissions;
+ use crate::creator::tests::create_document;
+ use crate::encryption::PasswordAlgorithm;
+ use rand::RngExt as _;
+
+ #[test]
+ fn authenticate_password_r2() {
+ let document = create_document();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ length: None,
+ version: 1,
+ revision: 2,
+ permissions: Permissions::all(),
+ ..Default::default()
+ };
+
+ let owner_password = "owner";
+ let user_password = "user";
+
+ // Sanitize the passwords.
+ let owner_password = algorithm.sanitize_password_r4(owner_password).unwrap();
+ let user_password = algorithm.sanitize_password_r4(user_password).unwrap();
+
+ // Compute the hashed values.
+ algorithm.owner_value = algorithm
+ .compute_hashed_owner_password_r4(Some(&owner_password), &user_password)
+ .unwrap();
+
+ algorithm.user_value = algorithm
+ .compute_hashed_user_password_r2(&document, &user_password)
+ .unwrap();
+
+ // Assert that the correct passwords authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, &owner_password)
+ .is_ok()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, &user_password)
+ .is_ok()
+ );
+
+ // Assert that the swapped passwords do not authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, user_password)
+ .is_err()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, owner_password)
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn authenticate_password_r3() {
+ let document = create_document();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ length: Some(40),
+ version: 2,
+ revision: 3,
+ permissions: Permissions::all(),
+ ..Default::default()
+ };
+
+ let owner_password = "owner";
+ let user_password = "user";
+
+ // Sanitize the passwords.
+ let owner_password = algorithm.sanitize_password_r4(owner_password).unwrap();
+ let user_password = algorithm.sanitize_password_r4(user_password).unwrap();
+
+ // Compute the hashed values.
+ algorithm.owner_value = algorithm
+ .compute_hashed_owner_password_r4(Some(&owner_password), &user_password)
+ .unwrap();
+
+ algorithm.user_value = algorithm
+ .compute_hashed_user_password_r3_r4(&document, &user_password)
+ .unwrap();
+
+ // Assert that the correct passwords authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, &owner_password)
+ .is_ok()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, &user_password)
+ .is_ok()
+ );
+
+ // Assert that the swapped passwords do not authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, user_password)
+ .is_err()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, owner_password)
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn authenticate_password_r4() {
+ let document = create_document();
+
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ length: Some(128),
+ version: 4,
+ revision: 4,
+ permissions: Permissions::all(),
+ ..Default::default()
+ };
+
+ let owner_password = "owner";
+ let user_password = "user";
+
+ // Sanitize the passwords.
+ let owner_password = algorithm.sanitize_password_r4(owner_password).unwrap();
+ let user_password = algorithm.sanitize_password_r4(user_password).unwrap();
+
+ // Compute the hashed values.
+ algorithm.owner_value = algorithm
+ .compute_hashed_owner_password_r4(Some(&owner_password), &user_password)
+ .unwrap();
+
+ algorithm.user_value = algorithm
+ .compute_hashed_user_password_r3_r4(&document, &user_password)
+ .unwrap();
+
+ // Assert that the correct passwords authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, &owner_password)
+ .is_ok()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, &user_password)
+ .is_ok()
+ );
+
+ // Assert that the swapped passwords do not authenticate.
+ assert!(
+ algorithm
+ .authenticate_owner_password_r4(&document, user_password)
+ .is_err()
+ );
+ assert!(
+ algorithm
+ .authenticate_user_password_r4(&document, owner_password)
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn authenticate_password_r5() {
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ version: 5,
+ revision: 5,
+ permissions: Permissions::all(),
+ ..Default::default()
+ };
+
+ let owner_password = "owner";
+ let user_password = "user";
+
+ // Sanitize the passwords.
+ let owner_password = algorithm.sanitize_password_r6(owner_password).unwrap();
+ let user_password = algorithm.sanitize_password_r6(user_password).unwrap();
+
+ // Compute the hashed values.
+ let mut file_encryption_key = [0u8; 32];
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ let (user_value, user_encrypted) = algorithm
+ .compute_hashed_user_password_r6(file_encryption_key, &user_password)
+ .unwrap();
+
+ algorithm.user_value = user_value;
+ algorithm.user_encrypted = user_encrypted;
+
+ let (owner_value, owner_encrypted) = algorithm
+ .compute_hashed_owner_password_r6(file_encryption_key, &owner_password)
+ .unwrap();
+
+ algorithm.owner_value = owner_value;
+ algorithm.owner_encrypted = owner_encrypted;
+
+ algorithm.permission_encrypted = algorithm.compute_permissions(file_encryption_key).unwrap();
+
+ // Assert that the correct passwords authenticate.
+ assert!(algorithm.authenticate_owner_password_r6(&owner_password).is_ok());
+ assert!(algorithm.authenticate_user_password_r6(&user_password).is_ok());
+
+ // Assert that the swapped passwords do not authenticate.
+ assert!(algorithm.authenticate_owner_password_r6(&user_password).is_err());
+ assert!(algorithm.authenticate_user_password_r6(&owner_password).is_err());
+
+ // Assert that the permissions validate correctly.
+ assert!(algorithm.validate_permissions(file_encryption_key).is_ok());
+
+ // Assert that the file encryption key is equal for the owner password.
+ let key = algorithm.compute_file_encryption_key_r6(&owner_password).unwrap();
+ assert_eq!(&file_encryption_key[..], key);
+
+ // Assert that the file encryption key is equal for the user password.
+ let key = algorithm.compute_file_encryption_key_r6(&user_password).unwrap();
+ assert_eq!(&file_encryption_key[..], key);
+ }
+
+ #[test]
+ fn authenticate_password_r6() {
+ let mut algorithm = PasswordAlgorithm {
+ encrypt_metadata: true,
+ version: 5,
+ revision: 6,
+ permissions: Permissions::all(),
+ ..Default::default()
+ };
+
+ let owner_password = "owner";
+ let user_password = "user";
+
+ // Sanitize the passwords.
+ let owner_password = algorithm.sanitize_password_r6(owner_password).unwrap();
+ let user_password = algorithm.sanitize_password_r6(user_password).unwrap();
+
+ // Compute the hashed values.
+ let mut file_encryption_key = [0u8; 32];
+
+ let mut rng = rand::rng();
+ rng.fill(&mut file_encryption_key);
+
+ let (user_value, user_encrypted) = algorithm
+ .compute_hashed_user_password_r6(file_encryption_key, &user_password)
+ .unwrap();
+
+ algorithm.user_value = user_value;
+ algorithm.user_encrypted = user_encrypted;
+
+ let (owner_value, owner_encrypted) = algorithm
+ .compute_hashed_owner_password_r6(file_encryption_key, &owner_password)
+ .unwrap();
+
+ algorithm.owner_value = owner_value;
+ algorithm.owner_encrypted = owner_encrypted;
+
+ algorithm.permission_encrypted = algorithm.compute_permissions(file_encryption_key).unwrap();
+
+ // Assert that the correct passwords authenticate.
+ assert!(algorithm.authenticate_owner_password_r6(&owner_password).is_ok());
+ assert!(algorithm.authenticate_user_password_r6(&user_password).is_ok());
+
+ // Assert that the swapped passwords do not authenticate.
+ assert!(algorithm.authenticate_owner_password_r6(&user_password).is_err());
+ assert!(algorithm.authenticate_user_password_r6(&owner_password).is_err());
+
+ // Assert that the permissions validate correctly.
+ assert!(algorithm.validate_permissions(file_encryption_key).is_ok());
+
+ // Assert that the file encryption key is equal for the owner password.
+ let key = algorithm.compute_file_encryption_key_r6(&owner_password).unwrap();
+ assert_eq!(&file_encryption_key[..], key);
+
+ // Assert that the file encryption key is equal for the user password.
+ let key = algorithm.compute_file_encryption_key_r6(&user_password).unwrap();
+ assert_eq!(&file_encryption_key[..], key);
+ }
+
+ /// Some PDF writers (e.g. Adobe) pad /O and /U to 127 bytes with trailing
+ /// zeros instead of the spec-required 48. Verify that `try_from` accepts
+ /// these and truncates to the correct 48-byte length.
+ #[test]
+ fn r6_padded_owner_user_values_accepted() {
+ use crate::{Document, Object, StringFormat, dictionary};
+
+ let mut doc = Document::with_version("2.0");
+
+ // Build valid 48-byte /O and /U (contents don't matter for parsing).
+ let o_48 = vec![0xAAu8; 48];
+ let u_48 = vec![0xBBu8; 48];
+
+ // Pad to 127 bytes with trailing zeros — mimics real-world Adobe PDFs.
+ let mut o_127 = o_48.clone();
+ o_127.resize(127, 0u8);
+ let mut u_127 = u_48.clone();
+ u_127.resize(127, 0u8);
+
+ let encrypt_dict = dictionary! {
+ "Filter" => "Standard",
+ "V" => Object::Integer(5),
+ "R" => Object::Integer(6),
+ "Length" => Object::Integer(256),
+ "O" => Object::String(o_127, StringFormat::Literal),
+ "OE" => Object::String(vec![0xCCu8; 32], StringFormat::Literal),
+ "U" => Object::String(u_127, StringFormat::Literal),
+ "UE" => Object::String(vec![0xDDu8; 32], StringFormat::Literal),
+ "P" => Object::Integer(-3388),
+ "Perms" => Object::String(vec![0xEEu8; 16], StringFormat::Literal)
+ };
+
+ let encrypt_id = doc.add_object(encrypt_dict);
+ doc.trailer.set("Encrypt", Object::Reference(encrypt_id));
+
+ let algo = PasswordAlgorithm::try_from(&doc).expect("should accept padded /O and /U longer than 48 bytes");
+
+ // Verify the values were truncated to the spec-required 48 bytes.
+ assert_eq!(algo.owner_value.len(), 48);
+ assert_eq!(algo.user_value.len(), 48);
+ assert_eq!(&algo.owner_value, &o_48);
+ assert_eq!(&algo.user_value, &u_48);
+ }
+
+ /// Verify that /O and /U values shorter than 48 bytes are still rejected
+ /// for R >= 5.
+ #[test]
+ fn r6_short_owner_user_values_rejected() {
+ use crate::{Document, Object, StringFormat, dictionary};
+
+ let mut doc = Document::with_version("2.0");
+
+ let encrypt_dict = dictionary! {
+ "Filter" => "Standard",
+ "V" => Object::Integer(5),
+ "R" => Object::Integer(6),
+ "Length" => Object::Integer(256),
+ "O" => Object::String(vec![0xAAu8; 47], StringFormat::Literal),
+ "OE" => Object::String(vec![0xCCu8; 32], StringFormat::Literal),
+ "U" => Object::String(vec![0xBBu8; 48], StringFormat::Literal),
+ "UE" => Object::String(vec![0xDDu8; 32], StringFormat::Literal),
+ "P" => Object::Integer(-3388),
+ "Perms" => Object::String(vec![0xEEu8; 16], StringFormat::Literal)
+ };
+
+ let encrypt_id = doc.add_object(encrypt_dict);
+ doc.trailer.set("Encrypt", Object::Reference(encrypt_id));
+
+ assert!(
+ PasswordAlgorithm::try_from(&doc).is_err(),
+ "should reject /O shorter than 48 bytes"
+ );
+ }
+}
diff --git a/vendor/lopdf/src/encryption/crypt_filters.rs b/vendor/lopdf/src/encryption/crypt_filters.rs
new file mode 100644
index 000000000..d7ec9584a
--- /dev/null
+++ b/vendor/lopdf/src/encryption/crypt_filters.rs
@@ -0,0 +1,275 @@
+use super::DecryptionError;
+use super::pkcs5::Pkcs5;
+use super::rc4::Rc4;
+use crate::ObjectId;
+use aes::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
+use md5::{Digest as _, Md5};
+use rand::RngExt as _;
+
+type Aes128CbcEnc = cbc::Encryptor<aes::Aes128>;
+type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
+
+type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;
+type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
+
+pub trait CryptFilter: std::fmt::Debug + Send + Sync {
+ fn method(&self) -> &[u8];
+ fn compute_key(&self, key: &[u8], obj_id: ObjectId) -> Result<Vec<u8>, DecryptionError>;
+ fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, DecryptionError>;
+ fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, DecryptionError>;
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct IdentityCryptFilter;
+
+impl CryptFilter for IdentityCryptFilter {
+ fn method(&self) -> &[u8] {
+ b"Identity"
+ }
+
+ fn compute_key(&self, key: &[u8], _obj_id: ObjectId) -> Result<Vec<u8>, DecryptionError> {
+ Ok(key.to_vec())
+ }
+
+ fn encrypt(&self, _key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ Ok(plaintext.to_vec())
+ }
+
+ fn decrypt(&self, _key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ Ok(ciphertext.to_vec())
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Rc4CryptFilter;
+
+impl CryptFilter for Rc4CryptFilter {
+ fn method(&self) -> &[u8] {
+ b"V2"
+ }
+
+ fn compute_key(&self, key: &[u8], obj_id: ObjectId) -> Result<Vec<u8>, DecryptionError> {
+ let mut hasher = Md5::new();
+
+ hasher.update(key);
+
+ // For all strings and streams without crypt filter specifier; treating the object number
+ // and generation number as binary integers, extend the original n-byte file encryption key
+ // to n + 5 bytes by appending the low-order 3 bytes of the object number and the low-order
+ // 2 bytes of the generation number in that order, low-order byte first.
+ hasher.update(&obj_id.0.to_le_bytes()[..3]);
+ hasher.update(&obj_id.1.to_le_bytes()[..2]);
+
+ // Initialise the MD5 hash function and pass the result of the previous step as an input to
+ // this function.
+ //
+ // Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5 hash as
+ // the key for the AES symmetric key algorithm.
+ let key_len = std::cmp::min(key.len() + 5, 16);
+ let key = hasher.finalize()[..key_len].to_vec();
+
+ Ok(key)
+ }
+
+ fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ Ok(Rc4::new(key).encrypt(plaintext))
+ }
+
+ fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ Ok(Rc4::new(key).decrypt(ciphertext))
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Aes128CryptFilter;
+
+impl CryptFilter for Aes128CryptFilter {
+ fn method(&self) -> &[u8] {
+ b"AESV2"
+ }
+
+ fn compute_key(&self, key: &[u8], obj_id: ObjectId) -> Result<Vec<u8>, DecryptionError> {
+ let mut builder = Vec::with_capacity(key.len() + 9);
+
+ builder.extend_from_slice(key);
+
+ // For all strings and streams without crypt filter specifier; treating the object number
+ // and generation number as binary integers, extend the original n-byte file encryption key
+ // to n + 5 bytes by appending the low-order 3 bytes of the object number and the low-order
+ // 2 bytes of the generation number in that order, low-order byte first.
+ builder.extend_from_slice(&obj_id.0.to_le_bytes()[..3]);
+ builder.extend_from_slice(&obj_id.1.to_le_bytes()[..2]);
+
+ // If using the AES algorithm, extend the file encryption key an additional 4 bytes by
+ // adding the value "sAlT".
+ builder.extend_from_slice(b"sAlT");
+
+ // Initialise the MD5 hash function and pass the result of the previous step as an input to
+ // this function.
+ //
+ // Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5 hash as
+ // the key for the AES symmetric key algorithm.
+ let key_len = std::cmp::min(key.len() + 5, 16);
+ let key = Md5::digest(builder)[..key_len].to_vec();
+
+ Ok(key)
+ }
+
+ fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ // Ensure that the key is 128 bits (i.e., 16 bytes).
+ if key.len() != 16 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+ let key: &[u8; 16] = key.try_into().map_err(|_| DecryptionError::InvalidKeyLength)?;
+
+ // The ciphertext needs to be a multiple of 16 bytes to include the padding.
+ let ciphertext_len = (plaintext.len() + 16) / 16 * 16;
+
+ // Allocate sufficient bytes for the initialization vector, the ciphertext and the padding
+ // combined.
+ let mut ciphertext = Vec::with_capacity(16 + ciphertext_len);
+
+ // Generate random numbers to populate the initialization vector.
+ let mut rng = rand::rng();
+ let mut iv = [0u8; 16];
+ rng.fill(&mut iv);
+
+ // Combine the IV and the plaintext.
+ ciphertext.extend_from_slice(&iv);
+ ciphertext.extend_from_slice(plaintext);
+ ciphertext.resize(16 + ciphertext_len, 0);
+
+ // Use the 128-bit AES-CBC algorithm with PKCS#5 padding to encrypt the plaintext.
+ //
+ // Strings and streams encrypted with AES shall use a padding scheme that is described in
+ // the Internet RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0;
+ // see the Bibliography. For an original message length of M, the pad shall consist of 16 -
+ // (M mod 16) bytes whose value shall also be 16 - (M mod 16).
+ Aes128CbcEnc::new(key.into(), &iv.into())
+ .encrypt_padded::<Pkcs5>(&mut ciphertext[16..], plaintext.len())
+ // Padding errors should not occur when encrypting, but avoid causing a panic.
+ .map_err(|_| DecryptionError::Padding)?;
+
+ Ok(ciphertext)
+ }
+
+ fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ // Ensure that the key is 128 bits (i.e., 16 bytes).
+ if key.len() != 16 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+ let key: &[u8; 16] = key.try_into().map_err(|_| DecryptionError::InvalidKeyLength)?;
+
+ // Ensure that the ciphertext length is a multiple of 16 bytes.
+ if !ciphertext.len().is_multiple_of(16) {
+ return Err(DecryptionError::InvalidCipherTextLength);
+ }
+
+ // There is nothing to decrypt if the ciphertext is empty or only contains the IV.
+ if ciphertext.is_empty() || ciphertext.len() == 16 {
+ return Ok(vec![]);
+ }
+
+ let mut iv = [0x00u8; 16];
+ iv.copy_from_slice(&ciphertext[..16]);
+
+ // Use the 128-bit AES-CBC algorithm with PKCS#5 padding to decrypt the ciphertext.
+ //
+ // Strings and streams encrypted with AES shall use a padding scheme that is described in
+ // the Internet RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0;
+ // see the Bibliography. For an original message length of M, the pad shall consist of 16 -
+ // (M mod 16) bytes whose value shall also be 16 - (M mod 16).
+ let data = &mut ciphertext[16..].to_vec();
+
+ Ok(Aes128CbcDec::new(key.into(), &iv.into())
+ .decrypt_padded::<Pkcs5>(data)
+ .map_err(|_| DecryptionError::Padding)?
+ .to_vec())
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Aes256CryptFilter;
+
+impl CryptFilter for Aes256CryptFilter {
+ fn method(&self) -> &[u8] {
+ b"AESV3"
+ }
+
+ fn compute_key(&self, key: &[u8], _obj_id: ObjectId) -> Result<Vec<u8>, DecryptionError> {
+ // Use the 32-byte file encryption key for the AES-256 symmetric key algorithm.
+ Ok(key.to_vec())
+ }
+
+ fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ // Ensure that the key is 256 bits (i.e., 32 bytes).
+ if key.len() != 32 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+ let key: &[u8; 32] = key.try_into().map_err(|_| DecryptionError::InvalidKeyLength)?;
+
+ // The ciphertext needs to be a multiple of 16 bytes to include the padding.
+ let ciphertext_len = (plaintext.len() + 16) / 16 * 16;
+
+ // Allocate sufficient bytes for the initialization vector, the ciphertext and the padding
+ // combined.
+ let mut ciphertext = Vec::with_capacity(16 + ciphertext_len);
+
+ // Generate random numbers to populate the initialization vector.
+ let mut rng = rand::rng();
+ let mut iv = [0u8; 16];
+ rng.fill(&mut iv);
+
+ // Combine the IV and the plaintext.
+ ciphertext.extend_from_slice(&iv);
+ ciphertext.extend_from_slice(plaintext);
+ ciphertext.resize(16 + ciphertext_len, 0);
+
+ // Use the 256-bit AES-CBC algorithm with PKCS#5 padding to encrypt the plaintext.
+ //
+ // Strings and streams encrypted with AES shall use a padding scheme that is described in
+ // the Internet RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0;
+ // see the Bibliography. For an original message length of M, the pad shall consist of 16 -
+ // (M mod 16) bytes whose value shall also be 16 - (M mod 16).
+ Aes256CbcEnc::new(key.into(), &iv.into())
+ .encrypt_padded::<Pkcs5>(&mut ciphertext[16..], plaintext.len())
+ // Padding errors should not occur when encrypting, but avoid causing a panic.
+ .map_err(|_| DecryptionError::Padding)?;
+
+ Ok(ciphertext)
+ }
+
+ fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, DecryptionError> {
+ // Ensure that the key is 256 bits (i.e., 32 bytes).
+ if key.len() != 32 {
+ return Err(DecryptionError::InvalidKeyLength);
+ }
+ let key: &[u8; 32] = key.try_into().map_err(|_| DecryptionError::InvalidKeyLength)?;
+
+ // Ensure that the ciphertext length is a multiple of 16 bytes.
+ if !ciphertext.len().is_multiple_of(16) {
+ return Err(DecryptionError::InvalidCipherTextLength);
+ }
+
+ // There is nothing to decrypt if the ciphertext is empty or only contains the IV.
+ if ciphertext.is_empty() || ciphertext.len() == 16 {
+ return Ok(vec![]);
+ }
+
+ let mut iv = [0x00u8; 16];
+ iv.copy_from_slice(&ciphertext[..16]);
+
+ // Use the 256-bit AES-CBC algorithm with PKCS#7 padding to decrypt the ciphertext.
+ //
+ // Strings and streams encrypted with AES shall use a padding scheme that is described in
+ // the Internet RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0;
+ // see the Bibliography. For an original message length of M, the pad shall consist of 16 -
+ // (M mod 16) bytes whose value shall also be 16 - (M mod 16).
+ let data = &mut ciphertext[16..].to_vec();
+
+ Ok(Aes256CbcDec::new(key.into(), &iv.into())
+ .decrypt_padded::<Pkcs5>(data)
+ .map_err(|_| DecryptionError::Padding)?
+ .to_vec())
+ }
+}
diff --git a/vendor/lopdf/src/encryption/pkcs5.rs b/vendor/lopdf/src/encryption/pkcs5.rs
new file mode 100644
index 000000000..4ab4bcb75
--- /dev/null
+++ b/vendor/lopdf/src/encryption/pkcs5.rs
@@ -0,0 +1,49 @@
+use aes::cipher::block_padding::{Error as PaddingError, Padding};
+
+/// Pad block with bytes with value equal to the number of bytes added.
+///
+/// PKCS#5 is described in [RFC 2898](https://tools.ietf.org/html/rfc2898).
+#[derive(Clone, Copy, Debug)]
+pub struct Pkcs5;
+
+impl Pkcs5 {
+ #[inline]
+ fn unpad(block: &[u8], strict: bool) -> Result<&[u8], PaddingError> {
+ // TODO: use bounds to check it at compile time
+ if block.len() > 16 {
+ panic!("block size is too big for PKCS#5");
+ }
+ let bs = block.len();
+ let n = block[bs - 1];
+ if n == 0 || n as usize > bs {
+ return Err(PaddingError);
+ }
+ let s = bs - n as usize;
+ if strict && block[s..bs - 1].iter().any(|&v| v != n) {
+ return Err(PaddingError);
+ }
+ Ok(&block[..s])
+ }
+}
+
+impl Padding for Pkcs5 {
+ #[inline]
+ fn raw_pad(block: &mut [u8], pos: usize) {
+ // TODO: use bounds to check it at compile time for Padding<B>
+ if block.len() > 16 {
+ panic!("block size is too big for PKCS#5");
+ }
+ if pos >= block.len() {
+ panic!("`pos` is bigger or equal to block size");
+ }
+ let n = (block.len() - pos) as u8;
+ for b in &mut block[pos..] {
+ *b = n;
+ }
+ }
+
+ #[inline]
+ fn raw_unpad(block: &[u8]) -> Result<&[u8], PaddingError> {
+ Pkcs5::unpad(block, true)
+ }
+}
diff --git a/vendor/lopdf/src/encryption/rc4.rs b/vendor/lopdf/src/encryption/rc4.rs
new file mode 100644
index 000000000..1047b41e6
--- /dev/null
+++ b/vendor/lopdf/src/encryption/rc4.rs
@@ -0,0 +1,66 @@
+// This module exists because the rust-crypto module is really old and not maintained.
+// Fortunately the RC4 algorithm is very simple to implement.
+pub struct Rc4 {
+ initial_state: [u8; 256],
+}
+
+impl Rc4 {
+ pub fn new<Key: AsRef<[u8]>>(key: Key) -> Self {
+ let key = key.as_ref();
+ assert!(!key.is_empty() && key.len() <= 256);
+
+ let mut initial_state = [0_u8; 256];
+ for (i, v) in initial_state.iter_mut().enumerate() {
+ *v = i as u8;
+ }
+
+ let mut j = 0_u8;
+ for i in 0..256 {
+ j = j.wrapping_add(initial_state[i]).wrapping_add(key[i % key.len()]);
+ initial_state.swap(i, j as usize);
+ }
+
+ Self { initial_state }
+ }
+
+ /// Encrypts/decrypts `input` into `output`. The shorter of `input` and `output`
+ /// determine how many bytes are written into `output`.
+ pub fn apply_keystream<'i, 'o, Input, Output>(&self, input: Input, output: Output)
+ where
+ Input: Iterator<Item = &'i u8>,
+ Output: Iterator<Item = &'o mut u8>,
+ {
+ let mut state = self.initial_state;
+ let mut i = 0_u8;
+ let mut j = 0_u8;
+ for (i_byte, o_byte) in input.zip(output) {
+ i = i.wrapping_add(1);
+ j = j.wrapping_add(state[i as usize]);
+ state.swap(i as usize, j as usize);
+ let key_byte = state[(state[i as usize].wrapping_add(state[j as usize])) as usize];
+ *o_byte = i_byte ^ key_byte;
+ }
+ }
+
+ /// Allocates a new Vec<u8> of the same length as `input` and decrypts
+ /// `input` into it.
+ pub fn decrypt<Input>(&self, input: Input) -> Vec<u8>
+ where
+ Input: AsRef<[u8]>,
+ {
+ let input = input.as_ref();
+ let mut output = vec![0; input.len()];
+ self.apply_keystream(input.iter(), output.iter_mut());
+ output
+ }
+
+ /// Allocates a new Vec<u8> of the same length as `input` and encrypts
+ /// `input` into it.
+ pub fn encrypt<Input>(&self, input: Input) -> Vec<u8>
+ where
+ Input: AsRef<[u8]>,
+ {
+ // Rc4 is symmetric
+ self.decrypt(input)
+ }
+}
diff --git a/vendor/lopdf/src/error.rs b/vendor/lopdf/src/error.rs
new file mode 100644
index 000000000..9e824d69a
--- /dev/null
+++ b/vendor/lopdf/src/error.rs
@@ -0,0 +1,170 @@
+use thiserror::Error;
+
+use crate::encodings::cmap::UnicodeCMapError;
+use crate::{ObjectId, encryption};
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(Debug, Error)]
+pub enum Error {
+ /// Lopdf does not (yet) implement a needed feature.
+ #[error(
+ "missing feature of lopdf: {0}; please open an issue at https://github.com/J-F-Liu/lopdf/ to let the developers know of your usecase"
+ )]
+ Unimplemented(&'static str),
+
+ /// An Object has the wrong type, e.g. the Object is an Array where a Name would be expected.
+ #[error("object has wrong type; expected type {expected} but found type {found}")]
+ ObjectType {
+ expected: &'static str,
+ found: &'static str,
+ },
+ #[error("dictionary has wrong type: ")]
+ DictType { expected: &'static str, found: String },
+ /// PDF document is already encrypted.
+ #[error("PDF document is already encrypted")]
+ AlreadyEncrypted,
+ /// The encountered character encoding is invalid.
+ #[error("invalid character encoding")]
+ CharacterEncoding,
+ /// The stream couldn't be decompressed.
+ #[error("couldn't decompress stream")]
+ Decompress(#[from] DecompressError),
+ /// Failed to parse input.
+ #[error("couldn't parse input")]
+ Parse(#[from] ParseError),
+ /// Error when decrypting the contents of the file
+ #[error("decryption error")]
+ Decryption(#[from] encryption::DecryptionError),
+ /// Dictionary key was not found.
+ #[error("missing required dictionary key \"{0}\"")]
+ DictKey(String),
+ /// Invalid inline image.
+ #[error("invalid inline image: {0}")]
+ InvalidInlineImage(String),
+ /// Invalid document outline.
+ #[error("invalid document outline: {0}")]
+ InvalidOutline(String),
+ /// Invalid stream.
+ #[error("invalid stream: {0}")]
+ InvalidStream(String),
+ /// Invalid object stream.
+ #[error("invalid object stream: {0}")]
+ InvalidObjectStream(String),
+ /// Byte offset in stream or file is invalid.
+ #[error("invalid byte offset")]
+ InvalidOffset(usize),
+ /// IO error
+ #[error("IO error")]
+ IO(#[from] std::io::Error),
+ // TODO: Maybe remove, as outline is not required in spec.
+ /// PDF document has no outline.
+ #[error("PDF document does not have an outline")]
+ NoOutline,
+ /// PDF document is not encrypted.
+ #[error("PDF document is not encrypted")]
+ NotEncrypted,
+ /// Invalid password provided for encrypted PDF.
+ #[error("invalid password for encrypted PDF")]
+ InvalidPassword,
+ /// Missing xref entry.
+ #[error("missing xref entry")]
+ MissingXrefEntry,
+ /// The Object ID was not found.
+ #[error("object ID {} {} not found", .0.0, .0.1)]
+ ObjectNotFound(ObjectId),
+ /// Dereferencing object failed due to a reference cycle.
+ #[error("reference cycle with object ID {} {}", .0.0, .0.1)]
+ ReferenceCycle(ObjectId),
+ /// Page number was not found in document.
+ #[error("page number not found")]
+ PageNumberNotFound(u32),
+ /// Numeric type cast failed.
+ #[error("numberic type cast failed: {0}")]
+ NumericCast(String),
+ /// Dereferencing object reached the limit.
+ /// This might indicate a reference loop.
+ #[error("dereferencing object reached limit, may indicate a reference cycle")]
+ ReferenceLimit,
+ /// Traversal of the document's object graph (e.g. a `/Kids`, `/First`, or `/Parent` chain)
+ /// exceeded the supported nesting depth.
+ /// This might indicate a reference cycle or a maliciously deep structure.
+ #[error("object graph traversal reached the nesting-depth limit, may indicate a reference cycle")]
+ RecursionLimit,
+ /// Decoding text string failed.
+ #[error("decoding text string failed")]
+ TextStringDecode,
+ /// Error while parsing cross reference table.
+ #[error("failed parsing cross reference table")]
+ Xref(#[from] XrefError),
+ /// Invalid indirect object while parsing at offset.
+ #[error("invalid indirect object at byte offset {offset}")]
+ IndirectObject { offset: usize },
+ /// Found object ID does not match expected object ID.
+ #[error("found object ID does not match expected object ID")]
+ ObjectIdMismatch,
+ /// Error when handling images.
+ #[cfg(feature = "embed_image")]
+ #[error("image error")]
+ Image(#[from] image::ImageError),
+ /// Syntax error while processing the content stream.
+ #[error("syntax error in content stream: {0}")]
+ Syntax(String),
+ /// Could not parse ToUnicodeCMap.
+ #[error("failed parsing ToUnicode CMap")]
+ ToUnicodeCMap(#[from] UnicodeCMapError),
+ #[error("converting integer")]
+ TryFromInt(#[from] std::num::TryFromIntError),
+ /// Encountered an unsupported security handler.
+ #[error("unsupported security handler")]
+ UnsupportedSecurityHandler(Vec<u8>),
+ /// Encountered when a differences code is out of bounds.
+ #[error("invalid encoding difference code: {code}")]
+ InvalidEncodingDifferenceCode { code: i64 },
+ /// Encountered when a differences glyph name is invalid.
+ #[error("invalid encoding difference glyph name: {name}")]
+ InvalidEncodingDifferenceGlyph { name: String },
+}
+
+#[derive(Error, Debug)]
+pub enum DecompressError {
+ #[error("decoding ASCII85 failed: {0}")]
+ Ascii85(&'static str),
+ #[error("decoding ASCIIHex failed: {0}")]
+ AsciiHex(&'static str),
+ #[error("applying the stream predictor failed: {0}")]
+ Predictor(&'static str),
+ /// The decompressed output exceeded the allowed size limit. This guards
+ /// against decompression bombs: a small compressed stream that inflates to
+ /// an enormous size (potentially exhausting memory). The `limit` is the
+ /// maximum number of output bytes that were permitted.
+ #[error("decompressed output exceeded the {limit}-byte limit (possible decompression bomb)")]
+ MemoryLimitExceeded { limit: usize },
+}
+
+#[derive(Error, Debug)]
+pub enum ParseError {
+ #[error("unexpected end of input")]
+ EndOfInput,
+ #[error("invalid content stream")]
+ InvalidContentStream,
+ #[error("invalid file header")]
+ InvalidFileHeader,
+ #[error("invalid file trailer")]
+ InvalidTrailer,
+ #[error("invalid cross reference table")]
+ InvalidXref,
+}
+
+#[derive(Debug, Error)]
+pub enum XrefError {
+ /// Could not find start of cross reference table.
+ #[error("invalid start value")]
+ Start,
+ /// The trailer's "Prev" field was invalid.
+ #[error("invalid start value in Prev field")]
+ PrevStart,
+ /// The trailer's "XRefStm" field was invalid.
+ #[error("invalid start value of XRefStm")]
+ StreamStart,
+}
diff --git a/vendor/lopdf/src/filters/mod.rs b/vendor/lopdf/src/filters/mod.rs
new file mode 100644
index 000000000..6717f3e5f
--- /dev/null
+++ b/vendor/lopdf/src/filters/mod.rs
@@ -0,0 +1 @@
+pub mod png;
diff --git a/vendor/lopdf/src/filters/png.rs b/vendor/lopdf/src/filters/png.rs
new file mode 100644
index 000000000..7ffced185
--- /dev/null
+++ b/vendor/lopdf/src/filters/png.rs
@@ -0,0 +1,159 @@
+use std::convert::{TryFrom, TryInto};
+use std::io::{Error, ErrorKind, Read, Result, Write};
+use std::mem;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FilterType {
+ None,
+ Sub,
+ Up,
+ Avg,
+ Paeth,
+}
+
+impl TryFrom<u8> for FilterType {
+ type Error = ();
+
+ fn try_from(n: u8) -> std::result::Result<FilterType, ()> {
+ match n {
+ 0 => Ok(FilterType::None),
+ 1 => Ok(FilterType::Sub),
+ 2 => Ok(FilterType::Up),
+ 3 => Ok(FilterType::Avg),
+ 4 => Ok(FilterType::Paeth),
+ _ => Err(()),
+ }
+ }
+}
+
+fn paeth_predict(left: u8, above: u8, upperleft: u8) -> u8 {
+ let expand_left = i16::from(left);
+ let expand_above = i16::from(above);
+ let expand_upperleft = i16::from(upperleft);
+
+ let initial_estimate = expand_left + expand_above - expand_upperleft;
+
+ let dist_left = (initial_estimate - expand_left).abs();
+ let dist_above = (initial_estimate - expand_above).abs();
+ let dist_upperleft = (initial_estimate - expand_upperleft).abs();
+
+ if dist_left <= dist_above && dist_left <= dist_upperleft {
+ left
+ } else if dist_above <= dist_upperleft {
+ above
+ } else {
+ upperleft
+ }
+}
+
+pub fn decode_row(filter: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
+ use self::FilterType::*;
+ let len = current.len();
+ let bpp = bpp.min(len);
+
+ match filter {
+ None => (),
+ Sub => {
+ for i in bpp..len {
+ current[i] = current[i].wrapping_add(current[i - bpp]);
+ }
+ }
+ Up => {
+ for i in 0..len {
+ current[i] = current[i].wrapping_add(previous[i]);
+ }
+ }
+ Avg => {
+ for i in 0..bpp {
+ current[i] = current[i].wrapping_add(previous[i] / 2);
+ }
+
+ for i in bpp..len {
+ current[i] =
+ current[i].wrapping_add(((i16::from(current[i - bpp]) + i16::from(previous[i])) / 2) as u8);
+ }
+ }
+ Paeth => {
+ for i in 0..bpp {
+ current[i] = current[i].wrapping_add(paeth_predict(0, previous[i], 0));
+ }
+
+ for i in bpp..len {
+ current[i] = current[i].wrapping_add(paeth_predict(current[i - bpp], previous[i], previous[i - bpp]));
+ }
+ }
+ }
+}
+
+pub fn decode_frame(content: &[u8], bpp: usize, bytes_per_row: usize) -> Result<Vec<u8>> {
+ // PrintCraft patch: each row is a filter byte plus `bytes_per_row` bytes, so a row longer
+ // than the data can never be read (`read_exact` below fails). Refuse it before allocating:
+ // a fuzzed `/Columns 4294967295` allocated two 4 GiB rows here.
+ if !content.is_empty() && bytes_per_row >= content.len() {
+ return Err(Error::new(ErrorKind::InvalidData, "PNG predictor row is longer than the data"));
+ }
+ let mut previous = Vec::new();
+ previous.try_reserve(bytes_per_row)?;
+ previous.resize(bytes_per_row, 0_u8);
+ let mut current = Vec::new();
+ current.try_reserve(bytes_per_row)?;
+ current.resize(bytes_per_row, 0_u8);
+ let mut decoded = Vec::new();
+ let mut pos = 0;
+ while pos < content.len() {
+ if let Ok(filter) = content[pos].try_into() {
+ pos += 1;
+ (&content[pos..]).read_exact(current.as_mut_slice())?;
+ pos += bytes_per_row;
+
+ decode_row(filter, bpp, previous.as_slice(), current.as_mut_slice());
+ decoded.write_all(current.as_slice())?;
+ mem::swap(&mut previous, &mut current);
+ } else {
+ return Err(Error::new(
+ ErrorKind::InvalidData,
+ format!("invalid PNG filter type ({})", content[pos]),
+ ));
+ }
+ }
+ Ok(decoded)
+}
+
+pub fn encode_row(method: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
+ use self::FilterType::*;
+ let len = current.len();
+ let bpp = bpp.min(len);
+
+ match method {
+ None => (),
+ Sub => {
+ for i in (bpp..len).rev() {
+ current[i] = current[i].wrapping_sub(current[i - bpp]);
+ }
+ }
+ Up => {
+ for i in 0..len {
+ current[i] = current[i].wrapping_sub(previous[i]);
+ }
+ }
+ Avg => {
+ for i in (bpp..len).rev() {
+ current[i] =
+ current[i].wrapping_sub(((u16::from(current[i - bpp]) + u16::from(previous[i])) / 2) as u8);
+ }
+
+ for i in 0..bpp {
+ current[i] = current[i].wrapping_sub(previous[i] / 2);
+ }
+ }
+ Paeth => {
+ for i in (bpp..len).rev() {
+ current[i] = current[i].wrapping_sub(paeth_predict(current[i - bpp], previous[i], previous[i - bpp]));
+ }
+
+ for i in 0..bpp {
+ current[i] = current[i].wrapping_sub(paeth_predict(0, previous[i], 0));
+ }
+ }
+ }
+}
diff --git a/vendor/lopdf/src/font.rs b/vendor/lopdf/src/font.rs
new file mode 100644
index 000000000..64d8b1321
--- /dev/null
+++ b/vendor/lopdf/src/font.rs
@@ -0,0 +1,188 @@
+/// This struct represents the data of a font.
+/// It contains information about the font's bounding box, ascent, descent, cap height, italic angle, and stemV.
+/// Reference: https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.5_v6.pdf
+#[derive(Debug, Clone)]
+pub struct FontData {
+ /// (Required) The PostScript name of the font. This should be the same as the value of BaseFont in the font or
+ /// CIDFont dictionary that refers to this font descriptor.
+ pub font_name: String,
+ /// (Required) A collection of flags defining various characteristics of the font.
+ pub flags: i64,
+ /// (Required, except for Type 3 fonts) A rectangle (see Section 3.8.4, “Rectangles”), expressed in the glyph
+ /// coordinate system, specifying the font bounding box. This is the smallest rectangle enclosing the shape that
+ /// would result if all of the glyphs of the font were placed with their origins coincident and then filled.
+ /// Format as: (x_min, y_min, x_max, y_max).
+ pub font_bbox: (i64, i64, i64, i64),
+ /// (Required) The angle, expressed in degrees counterclockwise from the vertical, of the dominant vertical strokes
+ /// of the font. (For example, the 9-o’clock position is 90 degrees, and the 3-o’clock position is –90 degrees.)
+ /// The value is negative for fonts that slope to the right, as almost all italic fonts do.
+ pub italic_angle: i64,
+ /// (Required, except for Type 3 fonts) The maximum height above the baseline reached by glyphs in this font,
+ /// excluding the height of glyphs for accentedc haracters.
+ pub ascent: i64,
+ /// (Required, except for Type 3 fonts) The maximum depth below the baseline reached by glyphs in this font. The
+ /// value is a negative number.
+ pub descent: i64,
+ /// (Required for fonts that have Latin characters, except for Type 3 fonts) The vertical coordinate of the top of
+ /// flat capital letters, measured from the baseline.
+ pub cap_height: i64,
+ /// (Required, except for Type 3 fonts) The thickness, measured horizontally, of the dominant vertical stems of
+ /// glyphs in the font.
+ pub stem_v: i64,
+ /// (Required) The name of a predefined CMap, or a stream containing a CMap program, that maps character codes to
+ /// font numbers and CIDs. If the descendant is a Type 2 CIDFont whose associated TrueType font program is not
+ /// embedded in the PDF file, the Encoding entry must be a predefined CMap name Read more (page 422): https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.5_v6.pdf
+ pub encoding: String,
+ /// (Required except for the standard 14 fonts) The first character code defined in
+ /// the font’s Widths array.
+ pub first_char: Option<i64>,
+ /// (Required except for the standard 14 fonts) The last character code defined in
+ /// the font’s Widths array.
+ pub last_char: Option<i64>,
+ /// (Required except for the standard 14 fonts; indirect reference preferred) An ar-
+ /// ray of (LastChar − FirstChar + 1) widths, each element being the glyph width
+ /// for the character code that equals FirstChar plus the array index. For charac-
+ /// ter codes outside the range FirstChar to LastChar, the value of MissingWidth
+ /// from the FontDescriptor entry for this font is used. The glyph widths are
+ /// measured in units in which 1000 units corresponds to 1 unit in text space.
+ /// These widths must be consistent with the actual widths given in the font pro-
+ /// gram itself. (See implementation note 53 in Appendix H.) For more informa-
+ /// tion on glyph widths and other glyph metrics, see Section 5.1.3, “Glyph
+ /// Positioning and Metrics.”
+ pub widths: Option<Vec<i64>>,
+ /// Size of the font data in bytes.
+ /// This is used to set the `Length1` key in the font stream dictionary.
+ font: Vec<u8>,
+}
+
+/// This struct is used to store font metadata extracted from a TrueType Fonts (TTF) file.
+/// # Examples
+///
+/// ```no_run
+/// // Read a TrueType Fonts (TTF) file.
+/// let font_file = std::fs::read("./SomeFont.ttf").unwrap();
+///
+/// // Create a new FontData instance.
+/// let font_name = "SomeFont".to_string();
+/// let font_data = lopdf::FontData::new(&font_file, font_name);
+/// ```
+///
+/// Also provides methods to set various font properties such as bounding box, italic angle, ascent, descent, and stemV.
+/// # Examples
+///
+/// ```no_run
+/// let font_file = std::fs::read("./SomeFont.ttf").unwrap();
+///
+/// // Create a new FontData instance along custome value.
+/// let font_data = lopdf::FontData::new(&font_file, "SomeFont".to_string())
+/// .set_stem_v(100)
+/// .set_italic_angle(10);
+/// ```
+impl FontData {
+ /// Create a new `FontData` instance by parsing the provided TTF file.
+ /// The TTF file is expected to be in bytes.
+ pub fn new(font_file: &[u8], font_name: String) -> Self {
+ use skrifa::MetadataProvider;
+ use skrifa::instance::{LocationRef, Size};
+
+ // Parse the TTF file using the skrifa crate
+ let font = skrifa::FontRef::new(font_file).expect("Failed to parse font file");
+
+ // Extract font metadata
+ // Note: The skrifa crate provides methods to get font bounding box, ascent, descent, cap height, italic
+ // angle, and stemV.
+ let metrics = font.metrics(Size::unscaled(), LocationRef::default());
+ let font_bbox = metrics.bounds.unwrap_or_default();
+ let ascent = metrics.ascent;
+ let descent = metrics.descent;
+ let cap_height = metrics.cap_height.unwrap_or(ascent);
+ let italic_angle = metrics.italic_angle;
+ let flags = 1; // Default flags, can be modified later if needed
+
+ // Calculate stemV based on the font bounding box
+ // Reference: https://stackoverflow.com/questions/35485179/stemv-value-of-the-truetype-font
+ // The stemV is typically calculated as 13% of the font's bbox width value.
+ let bbox_width = font_bbox.x_max - font_bbox.x_min;
+ let stem_v = (bbox_width as f64 * 0.13).round() as i64;
+
+ Self {
+ font_name,
+ flags,
+ font_bbox: (
+ font_bbox.x_min as i64,
+ font_bbox.y_min as i64,
+ font_bbox.x_max as i64,
+ font_bbox.y_max as i64,
+ ),
+ italic_angle: italic_angle.round() as i64,
+ ascent: ascent as i64,
+ descent: descent as i64,
+ cap_height: cap_height as i64,
+ stem_v,
+ encoding: "WinAnsiEncoding".to_string(), // Default encoding, can be modified later if needed
+ first_char: None,
+ last_char: None,
+ widths: None,
+ font: font_file.to_vec(),
+ }
+ }
+
+ pub fn set_flags(&mut self, flags: i64) -> &mut Self {
+ self.flags = flags;
+ self
+ }
+
+ pub fn set_font_bbox(&mut self, font_bbox: (i64, i64, i64, i64)) -> &mut Self {
+ self.font_bbox = font_bbox;
+ self
+ }
+
+ pub fn set_italic_angle(&mut self, italic_angle: i64) -> &mut Self {
+ self.italic_angle = italic_angle;
+ self
+ }
+
+ pub fn set_ascent(&mut self, ascent: i64) -> &mut Self {
+ self.ascent = ascent;
+ self
+ }
+
+ pub fn set_descent(&mut self, descent: i64) -> &mut Self {
+ self.descent = descent;
+ self
+ }
+
+ pub fn set_cap_height(&mut self, cap_height: i64) -> &mut Self {
+ self.cap_height = cap_height;
+ self
+ }
+
+ pub fn set_stem_v(&mut self, stem_v: i64) -> &mut Self {
+ self.stem_v = stem_v;
+ self
+ }
+
+ pub fn set_encoding(&mut self, encoding: String) -> &mut Self {
+ self.encoding = encoding;
+ self
+ }
+
+ pub fn set_first_char(&mut self, first_char: i64) -> &mut Self {
+ self.first_char = Some(first_char);
+ self
+ }
+
+ pub fn set_last_char(&mut self, last_char: i64) -> &mut Self {
+ self.last_char = Some(last_char);
+ self
+ }
+
+ pub fn set_widths(&mut self, widths: Vec<i64>) -> &mut Self {
+ self.widths = Some(widths);
+ self
+ }
+
+ pub fn bytes(&self) -> Vec<u8> {
+ self.font.clone()
+ }
+}
diff --git a/vendor/lopdf/src/incremental_document.rs b/vendor/lopdf/src/incremental_document.rs
new file mode 100644
index 000000000..b075ae97a
--- /dev/null
+++ b/vendor/lopdf/src/incremental_document.rs
@@ -0,0 +1,132 @@
+use crate::{Dictionary, Document, Object, ObjectId, Result};
+
+#[derive(Debug, Clone)]
+pub struct IncrementalDocument {
+ /// The raw data for the files read from input.
+ bytes_documents: Vec<u8>,
+
+ /// The combined result of `bytes_documents`.
+ /// Do not edit this document as it will not be saved.
+ prev_documents: Document,
+
+ /// A new document appended to the previously loaded file.
+ pub new_document: Document,
+}
+
+impl IncrementalDocument {
+ /// Create new PDF document.
+ pub fn new() -> Self {
+ Self {
+ bytes_documents: Vec::new(),
+ prev_documents: Document::new(),
+ new_document: Document::new(),
+ }
+ }
+
+ /// Create new `IncrementalDocument` from the bytes and document.
+ ///
+ /// The function expects the bytes and previous document to match.
+ /// If they do not match exactly this might result in broken PDFs.
+ pub fn create_from(prev_bytes: Vec<u8>, prev_documents: Document) -> Self {
+ Self {
+ bytes_documents: prev_bytes,
+ new_document: Document::new_from_prev(&prev_documents),
+ prev_documents,
+ }
+ }
+
+ /// Get the structure of the previous documents (all prev incremental updates combined.)
+ pub fn get_prev_documents(&self) -> &Document {
+ &self.prev_documents
+ }
+
+ /// Get the bytes of the previous documents.
+ pub fn get_prev_documents_bytes(&self) -> &[u8] {
+ &self.bytes_documents
+ }
+
+ /// Clone Object from previous document to new document.
+ /// If the object already exists nothing is done.
+ ///
+ /// This function can be used to clone an object so it can be changed in the incremental updates.
+ pub fn opt_clone_object_to_new_document(&mut self, object_id: ObjectId) -> Result<()> {
+ if !self.new_document.has_object(object_id) {
+ let old_object = self.prev_documents.get_object(object_id)?;
+ self.new_document.set_object(object_id, old_object.clone());
+ }
+ Ok(())
+ }
+
+ /// Get the page's resource dictionary (only in new document).
+ ///
+ /// Get Object that has the key `Resources`.
+ pub fn get_or_create_resources(&mut self, page_id: ObjectId) -> Result<&mut Object> {
+ self.opt_clone_object_to_new_document(page_id)?;
+ let resources_id = {
+ let page = self.new_document.get_object(page_id).and_then(Object::as_dict)?;
+ if page.has(b"Resources") {
+ page.get(b"Resources").and_then(Object::as_reference).ok()
+ } else {
+ None
+ }
+ };
+ if let Some(res_id) = resources_id {
+ self.opt_clone_object_to_new_document(res_id)?;
+ return self.new_document.get_object_mut(res_id);
+ }
+ let page = self
+ .new_document
+ .get_object_mut(page_id)
+ .and_then(Object::as_dict_mut)?;
+ if !page.has(b"Resources") {
+ page.set(b"Resources", Dictionary::new());
+ }
+ page.get_mut(b"Resources")
+ }
+
+ /// Add XObject to a page.
+ ///
+ /// Get Object that has the key `Resources -> XObject`.
+ pub fn add_xobject<N: Into<Vec<u8>>>(
+ &mut self, page_id: ObjectId, xobject_name: N, xobject_id: ObjectId,
+ ) -> Result<()> {
+ if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
+ if !resources.has(b"XObject") {
+ resources.set("XObject", Dictionary::new());
+ }
+ let mut xobjects = resources.get_mut(b"XObject")?;
+ if let Object::Reference(xobjects_ref_id) = xobjects {
+ let mut xobjects_id = *xobjects_ref_id;
+ while let Object::Reference(id) = self.new_document.get_object(xobjects_id)? {
+ xobjects_id = *id;
+ }
+ xobjects = self.new_document.get_object_mut(xobjects_id)?;
+ }
+ let xobjects = Object::as_dict_mut(xobjects)?;
+ xobjects.set(xobject_name, Object::Reference(xobject_id));
+ }
+ Ok(())
+ }
+
+ /// Add Graphics State to a page.
+ ///
+ /// Get Object that has the key `Resources -> ExtGState`.
+ pub fn add_graphics_state<N: Into<Vec<u8>>>(
+ &mut self, page_id: ObjectId, gs_name: N, gs_id: ObjectId,
+ ) -> Result<()> {
+ if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
+ if !resources.has(b"ExtGState") {
+ resources.set("ExtGState", Dictionary::new());
+ }
+ let states = resources.get_mut(b"ExtGState").and_then(Object::as_dict_mut)?;
+ states.set(gs_name, Object::Reference(gs_id));
+ }
+ Ok(())
+ }
+}
+
+impl Default for IncrementalDocument {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/vendor/lopdf/src/lib.rs b/vendor/lopdf/src/lib.rs
new file mode 100644
index 000000000..4c1d84531
--- /dev/null
+++ b/vendor/lopdf/src/lib.rs
@@ -0,0 +1,60 @@
+#![doc = include_str!("../README.md")]
+#![forbid(unsafe_code)]
+#![deny(clippy::all)]
+
+pub mod content;
+pub mod encryption;
+pub mod filters;
+pub mod xobject;
+pub mod xref;
+
+#[macro_use]
+mod object;
+mod document;
+mod incremental_document;
+
+mod bookmarks;
+mod cmap_section;
+mod common_data_structures;
+mod creator;
+mod datetime;
+mod destinations;
+mod encodings;
+mod error;
+mod outlines;
+mod processor;
+mod toc;
+mod writer;
+
+mod load_options;
+mod object_stream;
+mod parser;
+mod parser_aux;
+mod reader;
+mod save_options;
+
+#[cfg(feature = "font_embedding")]
+mod font;
+
+pub use document::Document;
+pub use object::{Dictionary, Object, ObjectId, Stream, StringFormat};
+
+pub use bookmarks::Bookmark;
+pub use common_data_structures::{decode_text_string, text_string};
+pub use destinations::Destination;
+pub use encodings::{Encoding, encode_utf8, encode_utf16_be};
+pub use encryption::{EncryptionState, EncryptionVersion, Permissions};
+pub use error::{DecompressError, Error, ParseError, Result};
+pub use incremental_document::IncrementalDocument;
+pub use load_options::{FilterFunc, LoadOptions};
+pub use object_stream::{ObjectStream, ObjectStreamBuilder, ObjectStreamConfig};
+pub use outlines::Outline;
+pub use reader::{PdfMetadata, Reader};
+pub use save_options::{SaveOptions, SaveOptionsBuilder};
+pub use toc::{Toc, TocType};
+
+pub use parser_aux::substr;
+pub use parser_aux::substring;
+
+#[cfg(feature = "font_embedding")]
+pub use font::FontData;
diff --git a/vendor/lopdf/src/load_options.rs b/vendor/lopdf/src/load_options.rs
new file mode 100644
index 000000000..6c4879c94
--- /dev/null
+++ b/vendor/lopdf/src/load_options.rs
@@ -0,0 +1,91 @@
+use crate::Object;
+
+/// Type alias for the filter function used during PDF loading.
+///
+/// The function receives an object ID and a mutable reference to the object,
+/// and returns `Some((id, object))` to keep it or `None` to discard it.
+pub type FilterFunc = fn((u32, u16), &mut Object) -> Option<((u32, u16), Object)>;
+
+/// Options for loading PDF documents.
+///
+/// Use this struct to configure password, object filtering, and strictness
+/// when loading a PDF. The default is lenient parsing with no password or filter.
+///
+/// # Examples
+///
+/// ```no_run
+/// use lopdf::{Document, LoadOptions};
+///
+/// // Load with a password
+/// let doc = Document::load_with_options(
+/// "encrypted.pdf",
+/// LoadOptions::with_password("secret"),
+/// );
+///
+/// // Load with strict parsing
+/// let doc = Document::load_with_options(
+/// "document.pdf",
+/// LoadOptions { strict: true, ..Default::default() },
+/// );
+/// ```
+#[derive(Clone, Default)]
+pub struct LoadOptions {
+ /// Password for encrypted PDFs.
+ pub password: Option<String>,
+ /// Object filter applied during loading.
+ pub filter: Option<FilterFunc>,
+ /// When `true`, reject non-conforming PDFs instead of silently accepting them.
+ /// Defaults to `false` (lenient parsing).
+ pub strict: bool,
+ /// Maximum number of bytes any single stream may decompress to during
+ /// loading (object streams and cross-reference streams).
+ ///
+ /// Compression filters can inflate a tiny input into an enormous output (a
+ /// "decompression bomb"). Because object and xref streams are decoded eagerly
+ /// while the document is loaded, an unbounded stream can exhaust memory
+ /// before any of your code runs. Set this to bound that per-stream cost when
+ /// loading untrusted PDFs; a stream that would exceed it fails with
+ /// [`crate::DecompressError::MemoryLimitExceeded`].
+ ///
+ /// `None` (the default) applies no limit.
+ pub max_decompressed_size: Option<usize>,
+}
+
+impl std::fmt::Debug for LoadOptions {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LoadOptions")
+ .field("password", &self.password.as_ref().map(|_| "***"))
+ .field("filter", &self.filter.map(|_| "fn(..)"))
+ .field("strict", &self.strict)
+ .field("max_decompressed_size", &self.max_decompressed_size)
+ .finish()
+ }
+}
+
+impl LoadOptions {
+ /// Create options with a password for encrypted PDFs.
+ pub fn with_password(password: &str) -> Self {
+ Self {
+ password: Some(password.to_string()),
+ ..Default::default()
+ }
+ }
+
+ /// Create options with an object filter.
+ pub fn with_filter(filter: FilterFunc) -> Self {
+ Self {
+ filter: Some(filter),
+ ..Default::default()
+ }
+ }
+
+ /// Create options that bound how large any single stream may decompress to
+ /// during loading, to defend against decompression bombs in untrusted PDFs.
+ /// See [`LoadOptions::max_decompressed_size`].
+ pub fn with_max_decompressed_size(max_decompressed_size: usize) -> Self {
+ Self {
+ max_decompressed_size: Some(max_decompressed_size),
+ ..Default::default()
+ }
+ }
+}
diff --git a/vendor/lopdf/src/object.rs b/vendor/lopdf/src/object.rs
new file mode 100644
index 000000000..3fdacf59f
--- /dev/null
+++ b/vendor/lopdf/src/object.rs
@@ -0,0 +1,1734 @@
+use crate::encodings;
+use crate::encodings::cmap::ToUnicodeCMap;
+use crate::encodings::{Differences, Encoding, Glyph};
+use crate::error::DecompressError;
+use crate::{Document, Error, Result};
+use indexmap::IndexMap;
+use log::warn;
+use std::cmp::max;
+use std::collections::HashSet;
+use std::fmt;
+use std::str;
+
+/// Object identifier consists of two parts: object number and generation number.
+pub type ObjectId = (u32, u16);
+
+/// Dictionary object.
+#[derive(Clone, Default, PartialEq)]
+pub struct Dictionary(IndexMap<Vec<u8>, Object>);
+
+/// Stream object
+/// Warning - all streams must be indirect objects, while
+/// the stream dictionary may be a direct object
+#[derive(Debug, Clone, PartialEq)]
+pub struct Stream {
+ /// Associated stream dictionary
+ pub dict: Dictionary,
+ /// Contents of the stream in bytes
+ pub content: Vec<u8>,
+ /// Can the stream be compressed by the `Document::compress()` function?
+ /// Font streams may not be compressed, for example
+ pub allows_compression: bool,
+ /// Stream data's position in PDF file.
+ pub start_position: Option<usize>,
+}
+
+/// Basic PDF object types defined in an enum.
+#[derive(Clone, PartialEq)]
+pub enum Object {
+ Null,
+ Boolean(bool),
+ Integer(i64),
+ Real(f32),
+ Name(Vec<u8>),
+ String(Vec<u8>, StringFormat),
+ Array(Vec<Object>),
+ Dictionary(Dictionary),
+ Stream(Stream),
+ Reference(ObjectId),
+}
+
+/// String objects can be written in two formats.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub enum StringFormat {
+ #[default]
+ Literal,
+ Hexadecimal,
+}
+
+impl From<bool> for Object {
+ fn from(value: bool) -> Self {
+ Object::Boolean(value)
+ }
+}
+
+impl From<i64> for Object {
+ fn from(number: i64) -> Self {
+ Object::Integer(number)
+ }
+}
+
+macro_rules! from_smaller_ints {
+ ($( $Int: ty )+) => {
+ $(
+ impl From<$Int> for Object {
+ fn from(number: $Int) -> Self {
+ Object::Integer(i64::from(number))
+ }
+ }
+ )+
+ }
+}
+
+from_smaller_ints! {
+ i8 i16 i32
+ u8 u16 u32
+}
+
+impl From<f64> for Object {
+ fn from(number: f64) -> Self {
+ Object::Real(number as f32)
+ }
+}
+
+impl From<f32> for Object {
+ fn from(number: f32) -> Self {
+ Object::Real(number)
+ }
+}
+
+impl From<String> for Object {
+ fn from(name: String) -> Self {
+ Object::Name(name.into_bytes())
+ }
+}
+
+impl<'a> From<&'a str> for Object {
+ fn from(name: &'a str) -> Self {
+ Object::Name(name.as_bytes().to_vec())
+ }
+}
+
+impl From<Vec<Object>> for Object {
+ fn from(array: Vec<Object>) -> Self {
+ Object::Array(array)
+ }
+}
+
+impl From<Dictionary> for Object {
+ fn from(dict: Dictionary) -> Self {
+ Object::Dictionary(dict)
+ }
+}
+
+impl From<Stream> for Object {
+ fn from(stream: Stream) -> Self {
+ Object::Stream(stream)
+ }
+}
+
+impl From<ObjectId> for Object {
+ fn from(id: ObjectId) -> Self {
+ Object::Reference(id)
+ }
+}
+
+impl Object {
+ pub fn string_literal<S: Into<Vec<u8>>>(s: S) -> Self {
+ Object::String(s.into(), StringFormat::Literal)
+ }
+
+ pub fn is_null(&self) -> bool {
+ matches!(*self, Object::Null)
+ }
+
+ pub fn as_bool(&self) -> Result<bool> {
+ match self {
+ Object::Boolean(value) => Ok(*value),
+ _ => Err(Error::ObjectType {
+ expected: "Boolean",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_i64(&self) -> Result<i64> {
+ match self {
+ Object::Integer(value) => Ok(*value),
+ _ => Err(Error::ObjectType {
+ expected: "Integer",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_f32(&self) -> Result<f32> {
+ match self {
+ Object::Real(value) => Ok(*value),
+ _ => Err(Error::ObjectType {
+ expected: "Real",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ /// Get the object value as a float.
+ /// Unlike [`Object::as_f32`] this will also cast an Integer to a Real.
+ pub fn as_float(&self) -> Result<f32> {
+ match self {
+ Object::Integer(value) => Ok(*value as f32),
+ Object::Real(value) => Ok(*value),
+ _ => Err(Error::ObjectType {
+ expected: "Integer or Real",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_name(&self) -> Result<&[u8]> {
+ match self {
+ Object::Name(name) => Ok(name),
+ _ => Err(Error::ObjectType {
+ expected: "Name",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_str(&self) -> Result<&[u8]> {
+ match self {
+ Object::String(string, _) => Ok(string),
+ _ => Err(Error::ObjectType {
+ expected: "String",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_str_mut(&mut self) -> Result<&mut Vec<u8>> {
+ match self {
+ Object::String(string, _) => Ok(string),
+ _ => Err(Error::ObjectType {
+ expected: "String",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_reference(&self) -> Result<ObjectId> {
+ match self {
+ Object::Reference(id) => Ok(*id),
+ _ => Err(Error::ObjectType {
+ expected: "Reference",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_array(&self) -> Result<&Vec<Object>> {
+ match self {
+ Object::Array(arr) => Ok(arr),
+ _ => Err(Error::ObjectType {
+ expected: "Array",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_array_mut(&mut self) -> Result<&mut Vec<Object>> {
+ match self {
+ Object::Array(arr) => Ok(arr),
+ _ => Err(Error::ObjectType {
+ expected: "Array",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_dict(&self) -> Result<&Dictionary> {
+ match self {
+ Object::Dictionary(dict) => Ok(dict),
+ _ => Err(Error::ObjectType {
+ expected: "Dictionary",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_dict_mut(&mut self) -> Result<&mut Dictionary> {
+ match self {
+ Object::Dictionary(dict) => Ok(dict),
+ _ => Err(Error::ObjectType {
+ expected: "Dictionary",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_stream(&self) -> Result<&Stream> {
+ match self {
+ Object::Stream(stream) => Ok(stream),
+ _ => Err(Error::ObjectType {
+ expected: "Stream",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn as_stream_mut(&mut self) -> Result<&mut Stream> {
+ match self {
+ Object::Stream(stream) => Ok(stream),
+ _ => Err(Error::ObjectType {
+ expected: "Stream",
+ found: self.enum_variant(),
+ }),
+ }
+ }
+
+ // TODO: maybe remove
+ pub fn type_name(&self) -> Result<&[u8]> {
+ match self {
+ Object::Dictionary(dict) => dict.get_type(),
+ Object::Stream(stream) => stream.dict.get_type(),
+ obj => Err(Error::ObjectType {
+ expected: "Dictionary or Stream",
+ found: obj.enum_variant(),
+ }),
+ }
+ }
+
+ pub fn enum_variant(&self) -> &'static str {
+ match self {
+ Object::Null => "Null",
+ Object::Boolean(_) => "Boolean",
+ Object::Integer(_) => "Integer",
+ Object::Real(_) => "Real",
+ Object::Name(_) => "Name",
+ Object::String(_, _) => "String",
+ Object::Array(_) => "Array",
+ Object::Dictionary(_) => "Dictionary",
+ Object::Stream(_) => "Stream",
+ Object::Reference(_) => "Reference",
+ }
+ }
+}
+
+impl fmt::Debug for Object {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Object::Null => write!(f, "Null"),
+ Object::Boolean(value) => write!(f, "{value}"),
+ Object::Integer(value) => write!(f, "{value}"),
+ Object::Real(value) => write!(f, "{value}"),
+ Object::Name(name) => write!(f, "/{}", String::from_utf8_lossy(name)),
+ Object::String(text, StringFormat::Literal) => write!(f, "({})", String::from_utf8_lossy(text)),
+ Object::String(text, StringFormat::Hexadecimal) => {
+ write!(f, "<")?;
+ for b in text {
+ write!(f, "{b:02x}")?
+ }
+ write!(f, ">")
+ }
+ Object::Array(array) => {
+ let items = array.iter().map(|item| format!("{item:?}")).collect::<Vec<String>>();
+ write!(f, "[{}]", items.join(" "))
+ }
+ Object::Dictionary(dict) => write!(f, "{dict:?}"),
+ Object::Stream(stream) => write!(f, "{:?}stream...endstream", stream.dict),
+ Object::Reference(id) => write!(f, "{} {} R", id.0, id.1),
+ }
+ }
+}
+
+impl Dictionary {
+ pub fn new() -> Dictionary {
+ Dictionary(IndexMap::new())
+ }
+
+ pub fn has(&self, key: &[u8]) -> bool {
+ self.0.contains_key(key)
+ }
+
+ pub fn get(&self, key: &[u8]) -> Result<&Object> {
+ self.0
+ .get(key)
+ .ok_or(Error::DictKey(String::from_utf8_lossy(key).to_string()))
+ }
+
+ /// Extract object from dictionary, dereferencing
+ /// the object if it is a reference.
+ pub fn get_deref<'a>(&'a self, key: &[u8], doc: &'a Document) -> Result<&'a Object> {
+ doc.dereference(self.get(key)?).map(|(_, object)| object)
+ }
+
+ pub fn get_mut(&mut self, key: &[u8]) -> Result<&mut Object> {
+ self.0
+ .get_mut(key)
+ .ok_or(Error::DictKey(String::from_utf8_lossy(key).to_string()))
+ }
+
+ pub fn set<K, V>(&mut self, key: K, value: V)
+ where
+ K: Into<Vec<u8>>,
+ V: Into<Object>,
+ {
+ self.0.insert(key.into(), value.into());
+ }
+
+ pub fn len(&self) -> usize {
+ self.0.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.0.len() == 0
+ }
+
+ pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
+ self.0.swap_remove(key)
+ }
+
+ pub fn has_type(&self, type_name: &[u8]) -> bool {
+ self.get(b"Type").and_then(|s| s.as_name()).ok() == Some(type_name)
+ }
+
+ pub fn get_type(&self) -> Result<&[u8]> {
+ self.get(b"Type")
+ .and_then(Object::as_name)
+ .or_else(|_| self.get(b"Linearized").and(Ok(b"Linearized")))
+ }
+
+ pub fn iter(&'_ self) -> indexmap::map::Iter<'_, Vec<u8>, Object> {
+ self.0.iter()
+ }
+
+ pub fn iter_mut(&'_ mut self) -> indexmap::map::IterMut<'_, Vec<u8>, Object> {
+ self.0.iter_mut()
+ }
+
+ pub fn get_font_encoding<'a>(&'a self, doc: &'a Document) -> Result<Encoding<'a>> {
+ self.get_font_encoding_inner(doc, None)
+ }
+
+ /// Resolve this font's encoding, bounding any decompression it performs (for
+ /// example decoding a `/ToUnicode` CMap stream) to `max_decompressed_size`
+ /// bytes. This is the decompression-bomb-safe counterpart to
+ /// [`Dictionary::get_font_encoding`]: it is used by
+ /// [`crate::Document::extract_text_with_limit`] so a crafted font stream
+ /// cannot inflate without limit. Unlike other encoding errors (which fall
+ /// back to standard encoding), a detected size-limit violation is propagated
+ /// as [`DecompressError::MemoryLimitExceeded`].
+ pub fn get_font_encoding_with_limit<'a>(
+ &'a self, doc: &'a Document, max_decompressed_size: usize,
+ ) -> Result<Encoding<'a>> {
+ self.get_font_encoding_inner(doc, Some(max_decompressed_size))
+ }
+
+ fn get_font_encoding_inner<'a>(&'a self, doc: &'a Document, limit: Option<usize>) -> Result<Encoding<'a>> {
+ if !self.has_type(b"Font") {
+ return Err(Error::DictType {
+ expected: "Font",
+ found: String::from_utf8_lossy(self.get_type().unwrap_or(b"None")).to_string(),
+ });
+ }
+
+ // Note: currently not all encodings are handled, not implemented:
+ // - TrueType cmap tables
+ // - DescendantFonts in CID-Keyed fonts
+ // - Predefined CJK CMAP other than indicated in SimpleEncoding
+ // - Deciding what should be the fallback font if no such encoding is defined in difference encoding (see Table
+ // 114 in 9.6.6.1 General under `BaseEncoding`).
+ let result = (|| {
+ if let Ok(object) = self.get(b"Encoding") {
+ return self.get_base_encoding(object, doc, limit);
+ }
+
+ if let Ok(stream) = self.get_deref(b"ToUnicode", doc).and_then(Object::as_stream) {
+ return self.get_to_unicode_encoding(stream, limit);
+ }
+
+ Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING))
+ })();
+
+ match result {
+ Ok(encoding) => Ok(encoding),
+ // A detected decompression bomb must surface, not be swallowed into a
+ // fallback encoding — otherwise the bounded caller's guard is silently
+ // defeated. Every other encoding error stays lenient, as before.
+ Err(err @ Error::Decompress(DecompressError::MemoryLimitExceeded { .. })) => Err(err),
+ Err(err) => {
+ warn!(
+ "Could not parse the encoding, error: {err:#?}\nFont: {self:#?}. Using standard encoding as a fallback!"
+ );
+ Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING))
+ }
+ }
+ }
+
+ /// Get a simple encoding from the /Encoding entry of a font dictionary.
+ fn get_base_encoding<'a>(
+ &'a self, mut object: &'a Object, doc: &'a Document, limit: Option<usize>,
+ ) -> Result<Encoding<'a>> {
+ // Set of visited to detect circular references.
+ let mut visited = HashSet::new();
+
+ loop {
+ match *object {
+ Object::Name(ref name) => {
+ return self.base_encoding(doc, name, limit);
+ }
+ Object::Reference(id) => {
+ if !visited.insert(id) {
+ return Err(Error::ReferenceCycle(id));
+ }
+
+ let Ok(o) = doc.get_object(id) else {
+ return Err(Error::ObjectNotFound(id));
+ };
+
+ object = o;
+ }
+ Object::Dictionary(ref dict) => {
+ let ty = dict.get(b"Type")?.as_name()?;
+
+ match ty {
+ b"Encoding" => {
+ let mut base = None;
+
+ if let Ok(base_encoding) = dict.get(b"BaseEncoding")
+ && let Ok(name) = base_encoding.as_name()
+ {
+ base = Some(self.base_encoding(doc, name, limit)?);
+ }
+
+ let base = match base {
+ Some(base) => base,
+ None => Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING),
+ };
+
+ let differences = dict.get(b"Differences")?.as_array()?;
+ let differences = self.differences(base, differences)?;
+ return Ok(Encoding::Differences(differences));
+ }
+ _ => {
+ return Err(Error::ObjectType {
+ expected: "Encoding Dictionary",
+ found: "Dictionary with Type other than /Encoding",
+ });
+ }
+ }
+ }
+ ref object => {
+ return Err(Error::ObjectType {
+ expected: "Name or Reference or Dictionary",
+ found: object.enum_variant(),
+ });
+ }
+ }
+ }
+ }
+
+ fn base_encoding<'a>(&'a self, doc: &'a Document, name: &'a [u8], limit: Option<usize>) -> Result<Encoding<'a>> {
+ match name {
+ b"StandardEncoding" => Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING)),
+ b"MacRomanEncoding" => Ok(Encoding::OneByteEncoding(&encodings::MAC_ROMAN_ENCODING)),
+ b"MacExpertEncoding" => Ok(Encoding::OneByteEncoding(&encodings::MAC_EXPERT_ENCODING)),
+ b"WinAnsiEncoding" => Ok(Encoding::OneByteEncoding(&encodings::WIN_ANSI_ENCODING)),
+ b"PDFDocEncoding" => {
+ log::warn!("PDFDocEncoding is not a valid character encoding for a font");
+ Ok(Encoding::OneByteEncoding(&encodings::PDF_DOC_ENCODING))
+ }
+ b"Identity-H" | b"Identity-V" => {
+ let stream = self.get_deref(b"ToUnicode", doc)?.as_stream()?;
+ self.get_to_unicode_encoding(stream, limit)
+ }
+ name => Ok(Encoding::SimpleEncoding(name)),
+ }
+ }
+
+ fn differences<'a>(&'a self, base: Encoding<'a>, array: &[Object]) -> Result<Differences<'a>> {
+ let mut map = IndexMap::new();
+ let mut inverse = IndexMap::new();
+ let mut current_code = 0;
+
+ for obj in array {
+ match *obj {
+ Object::Integer(code) => {
+ if !(0..=255).contains(&code) {
+ return Err(Error::InvalidEncodingDifferenceCode { code });
+ }
+
+ current_code = code as u8;
+ }
+ Object::Name(ref name) => {
+ let Some(glyph) = Glyph::from_name(name) else {
+ return Err(Error::InvalidEncodingDifferenceGlyph {
+ name: String::from_utf8_lossy(name).into_owned(),
+ });
+ };
+
+ map.insert(current_code, glyph);
+ inverse.insert(glyph, current_code);
+ current_code = current_code.wrapping_add(1);
+ }
+ _ => {
+ return Err(Error::ObjectType {
+ expected: "Integer or Name",
+ found: obj.enum_variant(),
+ });
+ }
+ }
+ }
+
+ Ok(Differences {
+ base: Box::new(base),
+ map,
+ inverse,
+ })
+ }
+
+ fn get_to_unicode_encoding(&'_ self, stream: &Stream, limit: Option<usize>) -> Result<Encoding<'_>> {
+ let content = match limit {
+ Some(max) => stream.get_plain_content_with_limit(max)?,
+ None => stream.get_plain_content()?,
+ };
+ let cmap = ToUnicodeCMap::parse(content)?;
+ Ok(Encoding::UnicodeMapEncoding(cmap))
+ }
+
+ pub fn extend(&mut self, other: &Dictionary) {
+ let keep_both_objects =
+ |new_dict: &mut IndexMap<Vec<u8>, Object>, key: &Vec<u8>, value: &Object, old_value: Object| {
+ let mut final_array;
+
+ match value {
+ Object::Array(array) => {
+ final_array = Vec::with_capacity(array.len() + 1);
+ final_array.push(old_value);
+ final_array.extend(array.to_owned());
+ }
+ _ => {
+ final_array = vec![value.to_owned(), old_value];
+ }
+ }
+
+ new_dict.insert(key.to_owned(), Object::Array(final_array));
+ };
+
+ let mut new_dict = std::mem::take(&mut self.0);
+ new_dict.reserve_exact(other.0.len());
+
+ for (key, value) in other.0.iter() {
+ if let Some(old_value) = new_dict.get(key) {
+ let old_value = old_value.to_owned();
+ match (&old_value, value) {
+ (Object::Dictionary(old_dict), Object::Dictionary(dict)) => {
+ let mut replaced_dict = old_dict.to_owned();
+ replaced_dict.extend(dict);
+ new_dict.insert(key.to_owned(), Object::Dictionary(replaced_dict));
+ }
+ (Object::Array(old_array), Object::Array(array)) => {
+ let mut replaced_array = old_array.to_owned();
+ replaced_array.extend(array.to_owned());
+ new_dict.insert(key.to_owned(), Object::Array(replaced_array));
+ }
+ (Object::Integer(old_id), Object::Integer(id)) => {
+ let array = vec![Object::Integer(*old_id), Object::Integer(*id)];
+ new_dict.insert(key.to_owned(), Object::Array(array));
+ }
+ (Object::Real(old_id), Object::Real(id)) => {
+ let array = vec![Object::Real(*old_id), Object::Real(*id)];
+ new_dict.insert(key.to_owned(), Object::Array(array));
+ }
+ (Object::String(old_ids, old_format), Object::String(ids, format)) => {
+ let array = vec![
+ Object::String(old_ids.to_owned(), old_format.to_owned()),
+ Object::String(ids.to_owned(), format.to_owned()),
+ ];
+ new_dict.insert(key.to_owned(), Object::Array(array));
+ }
+ (Object::Reference(old_object_id), Object::Reference(object_id)) => {
+ let array = vec![Object::Reference(*old_object_id), Object::Reference(*object_id)];
+ new_dict.insert(key.to_owned(), Object::Array(array));
+ }
+ (Object::Null, _) | (Object::Boolean(_), _) | (Object::Name(_), _) | (Object::Stream(_), _) => {
+ new_dict.insert(key.to_owned(), old_value);
+ }
+ (_, _) => keep_both_objects(&mut new_dict, key, value, old_value),
+ }
+ } else {
+ new_dict.insert(key.to_owned(), value.to_owned());
+ }
+ }
+
+ self.0 = new_dict;
+ }
+
+ /// Return a reference to the inner [`IndexMap`].
+ pub fn as_hashmap(&self) -> &IndexMap<Vec<u8>, Object> {
+ &self.0
+ }
+
+ /// Return a mut reference to the inner [`IndexMap`].
+ pub fn as_hashmap_mut(&mut self) -> &mut IndexMap<Vec<u8>, Object> {
+ &mut self.0
+ }
+}
+
+#[macro_export]
+macro_rules! dictionary {
+ () => {
+ $crate::Dictionary::new()
+ };
+ ($( $key: expr => $value: expr ),+ ,) => {
+ dictionary!( $($key => $value),+ )
+ };
+ ($( $key: expr => $value: expr ),*) => {{
+ let mut dict = $crate::Dictionary::new();
+ $(
+ dict.set($key, $value);
+ )*
+ dict
+ }}
+}
+
+impl fmt::Debug for Dictionary {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let entries = self
+ .into_iter()
+ .map(|(key, value)| format!("/{} {:?}", String::from_utf8_lossy(key), value))
+ .collect::<Vec<String>>();
+ write!(f, "<<{}>>", entries.concat())
+ }
+}
+
+impl IntoIterator for Dictionary {
+ type Item = (Vec<u8>, Object);
+ type IntoIter = indexmap::map::IntoIter<Vec<u8>, Object>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.0.into_iter()
+ }
+}
+
+impl<'a> IntoIterator for &'a Dictionary {
+ type Item = (&'a Vec<u8>, &'a Object);
+ type IntoIter = indexmap::map::Iter<'a, Vec<u8>, Object>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.0.iter()
+ }
+}
+
+impl<'a> IntoIterator for &'a mut Dictionary {
+ type Item = (&'a Vec<u8>, &'a mut Object);
+ type IntoIter = indexmap::map::IterMut<'a, Vec<u8>, Object>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.0.iter_mut()
+ }
+}
+
+use std::iter::FromIterator;
+impl<K: Into<Vec<u8>>> FromIterator<(K, Object)> for Dictionary {
+ fn from_iter<I: IntoIterator<Item = (K, Object)>>(iter: I) -> Self {
+ let mut dict = Dictionary::new();
+ for (k, v) in iter {
+ dict.set(k, v);
+ }
+ dict
+ }
+}
+
+/// A [`std::io::Write`] adapter that appends to a `Vec<u8>` but refuses to grow
+/// it past `limit` bytes. Used to bound decoders (e.g. LZW) that write into a
+/// sink rather than being read from, so a decompression bomb cannot allocate an
+/// unbounded amount of memory. On overflow it fills up to exactly `limit` bytes
+/// and then returns an error, so the caller can detect the overflow by length.
+struct LimitedWriter<'a> {
+ inner: &'a mut Vec<u8>,
+ limit: usize,
+}
+
+impl<'a> LimitedWriter<'a> {
+ fn new(inner: &'a mut Vec<u8>, limit: usize) -> Self {
+ LimitedWriter { inner, limit }
+ }
+}
+
+impl std::io::Write for LimitedWriter<'_> {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ let remaining = self.limit.saturating_sub(self.inner.len());
+ if buf.len() > remaining {
+ // Fill up to the limit so the caller's `len() > max` check trips,
+ // then signal that no more may be written.
+ self.inner.extend_from_slice(&buf[..remaining]);
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::WriteZero,
+ "decompression output exceeded limit",
+ ));
+ }
+ self.inner.extend_from_slice(buf);
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+impl Stream {
+ pub fn new(mut dict: Dictionary, content: Vec<u8>) -> Stream {
+ dict.set("Length", content.len() as i64);
+ Stream {
+ dict,
+ content,
+ allows_compression: true,
+ start_position: None,
+ }
+ }
+
+ pub fn with_position(dict: Dictionary, position: usize) -> Stream {
+ Stream {
+ dict,
+ content: vec![],
+ allows_compression: true,
+ start_position: Some(position),
+ }
+ }
+
+ /// Default is that the stream may be compressed. On font streams,
+ /// set this to false, otherwise the font will be corrupt
+ #[inline]
+ pub fn with_compression(mut self, allows_compression: bool) -> Stream {
+ self.allows_compression = allows_compression;
+ self
+ }
+
+ pub fn filters(&self) -> Result<Vec<&[u8]>> {
+ let filter = self.dict.get(b"Filter")?;
+
+ if let Ok(name) = filter.as_name() {
+ Ok(vec![name])
+ } else if let Ok(names) = filter.as_array() {
+ names.iter().map(Object::as_name).collect()
+ } else {
+ Err(Error::ObjectType {
+ expected: "Name or Array",
+ found: filter.enum_variant(),
+ })
+ }
+ }
+
+ pub fn set_content(&mut self, content: Vec<u8>) {
+ self.content = content;
+ self.dict.set("Length", self.content.len() as i64);
+ }
+
+ pub fn set_plain_content(&mut self, content: Vec<u8>) {
+ self.dict.remove(b"DecodeParms");
+ self.dict.remove(b"Filter");
+ self.dict.set("Length", content.len() as i64);
+ self.content = content;
+ }
+
+ pub fn get_plain_content(&self) -> Result<Vec<u8>> {
+ match self.filters() {
+ Ok(vec) if !vec.is_empty() => self.decompressed_content(),
+ _ => Ok(self.content.clone()),
+ }
+ }
+
+ /// Bomb-safe counterpart to [`Stream::get_plain_content`]: decode the stream,
+ /// rejecting it with [`DecompressError::MemoryLimitExceeded`] if the output
+ /// would exceed `max_output` bytes. An uncompressed stream whose raw content
+ /// already exceeds the limit is rejected too.
+ pub fn get_plain_content_with_limit(&self, max_output: usize) -> Result<Vec<u8>> {
+ match self.filters() {
+ Ok(vec) if !vec.is_empty() => self.decompressed_content_with_limit(max_output),
+ _ => {
+ if self.content.len() > max_output {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max_output }.into());
+ }
+ Ok(self.content.clone())
+ }
+ }
+ }
+
+ pub fn compress(&mut self) -> Result<()> {
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+ use std::io::prelude::*;
+
+ if self.dict.get(b"Filter").is_err() {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ encoder.write_all(self.content.as_slice())?;
+ let compressed = encoder.finish()?;
+ if compressed.len() + 19 < self.content.len() {
+ self.dict.set("Filter", "FlateDecode");
+ self.set_content(compressed);
+ }
+ }
+ Ok(())
+ }
+
+ /// Decode this stream's content, applying its filters in order.
+ ///
+ /// # Warning: unbounded output
+ ///
+ /// This method places **no limit** on the size of the decompressed output.
+ /// A small compressed stream can inflate to an enormous size (a
+ /// "decompression bomb"), so calling this on untrusted input can exhaust
+ /// all available memory. When processing PDFs from an untrusted source,
+ /// prefer [`Stream::decompressed_content_with_limit`] or
+ /// [`Stream::decompress_to_writer`], and load documents with
+ /// [`crate::LoadOptions::max_decompressed_size`] set.
+ pub fn decompressed_content(&self) -> Result<Vec<u8>> {
+ self.decode_filters(None)
+ }
+
+ /// Decode this stream's content, rejecting the stream with
+ /// [`DecompressError::MemoryLimitExceeded`] if the decoded output would
+ /// exceed `max_output` bytes.
+ ///
+ /// This is the bomb-safe counterpart to [`Stream::decompressed_content`].
+ /// Each filter in the chain is bounded individually, so a stream with nested
+ /// filters (e.g. `/Filter [FlateDecode FlateDecode]`) can never allocate
+ /// more than roughly `max_output` bytes per layer before being rejected,
+ /// rather than expanding without limit.
+ pub fn decompressed_content_with_limit(&self, max_output: usize) -> Result<Vec<u8>> {
+ self.decode_filters(Some(max_output))
+ }
+
+ /// Decode this stream's content into a caller-provided writer, rejecting the
+ /// stream if the decoded output would exceed `max_output` bytes.
+ ///
+ /// The result is decoded with the same bomb-safe bound as
+ /// [`Stream::decompressed_content_with_limit`] (internal buffering is capped
+ /// at roughly `max_output` bytes) and then written to `writer`, which lets
+ /// callers direct the output straight into a file or a fixed-capacity buffer
+ /// of their choosing. Returns the number of bytes written on success, or
+ /// [`DecompressError::MemoryLimitExceeded`] if the limit would be exceeded.
+ pub fn decompress_to_writer<W: std::io::Write>(&self, writer: &mut W, max_output: usize) -> Result<usize> {
+ let data = self.decompressed_content_with_limit(max_output)?;
+ writer.write_all(&data)?;
+ Ok(data.len())
+ }
+
+ /// Shared decoder for [`Stream::decompressed_content`] and its bounded
+ /// variants. `limit` is `None` to decode without a size limit, or
+ /// `Some(max)` to cap the decoded output at `max` bytes per filter layer.
+ fn decode_filters(&self, limit: Option<usize>) -> Result<Vec<u8>> {
+ let params = self.dict.get(b"DecodeParms").and_then(Object::as_dict).ok();
+ let filters = match self.filters() {
+ Ok(f) => f,
+ // No /Filter key means the stream is uncompressed. The raw content is
+ // already in memory, but still honor the caller's limit.
+ Err(_) => {
+ if let Some(max) = limit
+ && self.content.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ return Ok(self.content.clone());
+ }
+ };
+
+ let mut input = self.content.as_slice();
+ let mut output = vec![];
+
+ // Filters are in decoding order.
+ for filter in filters {
+ output = match filter {
+ b"FlateDecode" => Self::decompress_zlib(input, params, limit)?,
+ b"BrotliDecode" => Self::decompress_brotli(input, limit)?,
+ b"LZWDecode" => Self::decompress_lzw(input, params, limit)?,
+ b"ASCII85Decode" => Self::decode_ascii85(input, limit)?,
+ b"ASCIIHexDecode" => Self::decode_ascii_hex(input, limit)?,
+ b"RunLengthDecode" => Self::decode_run_length(input, limit)?,
+ _ => return Err(Error::Unimplemented("decompression algorithms")),
+ };
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ input = &output;
+ }
+ Ok(output)
+ }
+
+ fn decompress_brotli(input: &[u8], limit: Option<usize>) -> Result<Vec<u8>> {
+ use brotli_decompressor::Decompressor;
+
+ // Unlike the Flate path there is no fallback (e.g. raw deflate), so a
+ // truncated or corrupt stream fails hard instead of yielding partial
+ // output — intentional for a new filter, not an oversight.
+ let initial_capacity = match limit {
+ Some(max) => input.len().saturating_mul(2).min(max.saturating_add(1)),
+ None => input.len().saturating_mul(2),
+ };
+ let mut output = Vec::with_capacity(initial_capacity);
+ Self::read_capped(Decompressor::new(input, 4096), &mut output, limit)
+ .map_err(|err| Error::InvalidStream(format!("Brotli decompression failed: {err}")))?;
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ // /DecodeParms predictors are deliberately NOT applied here. The PDF
+ // Association's prototype files never pair /BrotliDecode with a
+ // /Predictor (their Brotli xref streams store raw W entries), pdf.js
+ // and pypdf ignore the parameters too; only MuPDF applies them.
+ // Applying them would also corrupt [/BrotliDecode /FlateDecode]
+ // chains, since the shared dict-form /DecodeParms is passed to every
+ // filter and a predictor there belongs to the Flate layer.
+ Ok(output)
+ }
+
+ /// Read `reader` to end, appending to `output`. When `limit` is `Some(max)`,
+ /// at most `max + 1` bytes are read, so an oversized (bomb) stream is
+ /// detected via the `> max` check by the caller without ever allocating the
+ /// full decompressed output.
+ fn read_capped<R: std::io::Read>(reader: R, output: &mut Vec<u8>, limit: Option<usize>) -> std::io::Result<()> {
+ use std::io::Read;
+ match limit {
+ Some(max) => Read::take(reader, (max as u64).saturating_add(1))
+ .read_to_end(output)
+ .map(|_| ()),
+ None => {
+ let mut reader = reader;
+ reader.read_to_end(output).map(|_| ())
+ }
+ }
+ }
+
+ fn decompress_lzw(input: &[u8], params: Option<&Dictionary>, limit: Option<usize>) -> Result<Vec<u8>> {
+ use weezl::{BitOrder, decode::Decoder};
+ const MIN_BITS: u8 = 9;
+
+ let early_change = params
+ .and_then(|p| p.get(b"EarlyChange").ok())
+ .and_then(|p| Object::as_i64(p).ok())
+ .map(|v| v != 0)
+ .unwrap_or(true);
+
+ let mut decoder = if early_change {
+ Decoder::with_tiff_size_switch(BitOrder::Msb, MIN_BITS - 1)
+ } else {
+ Decoder::new(BitOrder::Msb, MIN_BITS - 1)
+ };
+
+ let output = Self::decompress_lzw_loop(input, &mut decoder, limit);
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ Self::decompress_predictor(output, params)
+ }
+
+ fn decompress_lzw_loop(input: &[u8], decoder: &mut weezl::decode::Decoder, limit: Option<usize>) -> Vec<u8> {
+ let mut output = vec![];
+
+ // When a limit is set, decode into a writer that stops accepting bytes
+ // once `max + 1` have been produced, so a bomb cannot allocate the full
+ // (potentially enormous) output; the caller rejects it via the `> max`
+ // check. Without a limit, decode straight into the output vector.
+ let status = match limit {
+ Some(max) => {
+ let mut sink = LimitedWriter::new(&mut output, max.saturating_add(1));
+ decoder.into_stream(&mut sink).decode_all(input).status
+ }
+ None => decoder.into_stream(&mut output).decode_all(input).status,
+ };
+ if let Err(err) = status {
+ warn!("{err}");
+ }
+
+ output
+ }
+
+ fn decompress_zlib(input: &[u8], params: Option<&Dictionary>, limit: Option<usize>) -> Result<Vec<u8>> {
+ use flate2::read::ZlibDecoder;
+
+ // Reserve a starting capacity, but never pre-allocate beyond the limit so
+ // a bomb cannot force a huge allocation up front.
+ let initial_capacity = match limit {
+ Some(max) => input.len().saturating_mul(2).min(max.saturating_add(1)),
+ None => input.len().saturating_mul(2),
+ };
+ let mut output = Vec::with_capacity(initial_capacity);
+
+ if !input.is_empty()
+ && let Err(err) = Self::read_capped(ZlibDecoder::new(input), &mut output, limit)
+ {
+ warn!("{err}");
+ // Zlib decompression failed (e.g. corrupt adler32 checksum in
+ // encrypted PDFs). Retry with raw deflate, skipping the 2-byte
+ // zlib header and ignoring the checksum.
+ if output.is_empty() && input.len() > 2 {
+ use flate2::read::DeflateDecoder;
+ if let Err(raw_err) = Self::read_capped(DeflateDecoder::new(&input[2..]), &mut output, limit) {
+ warn!("raw deflate fallback also failed: {raw_err}");
+ }
+ }
+ }
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ Self::decompress_predictor(output, params)
+ }
+
+ fn decode_ascii85(input: &[u8], limit: Option<usize>) -> Result<Vec<u8>> {
+ let mut output = vec![];
+ let mut buffer: u32 = 0;
+ let mut count = 0;
+ // Check for EOD marker
+ let input_no_eod = if input.len() >= 2 && &input[input.len() - 2..] == b"~>" {
+ &input[..input.len() - 2]
+ } else {
+ log::warn!("ASCII85 stream is missing its EOD marker");
+ input
+ };
+ for &ch in input_no_eod {
+ // ASCII85 can amplify up to 4x (each `z` expands to four zero bytes),
+ // so bound the output here rather than only after the fact; each
+ // iteration appends at most 4 bytes, so output never exceeds max + 4.
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ if ch == b'z' {
+ if count != 0 {
+ return Err(DecompressError::Ascii85("z character is not allowed in the middle of a group").into());
+ }
+ output.extend_from_slice(&[0, 0, 0, 0]);
+ continue;
+ }
+
+ if ch.is_ascii_whitespace() {
+ continue;
+ }
+
+ if !(b'!'..=b'u').contains(&ch) {
+ break;
+ }
+ // A base-85 group encodes a value in 0..2^32; reject any group whose
+ // value reaches 2^32. Both the multiply and the add can carry past
+ // u32::MAX (2^32-1 == 85 * 50529027, so a prefix of 50529027 leaves
+ // the multiply in range yet the add still overflows), so guard both.
+ buffer = buffer
+ .checked_mul(85)
+ .and_then(|b| b.checked_add((ch - b'!') as u32))
+ .ok_or(DecompressError::Ascii85("group value out of range"))?;
+ count += 1;
+
+ if count == 5 {
+ output.extend_from_slice(&buffer.to_be_bytes());
+ buffer = 0;
+ count = 0;
+ }
+ }
+
+ if count > 0 {
+ for _ in count..5 {
+ buffer = buffer
+ .checked_mul(85)
+ .and_then(|b| b.checked_add(84))
+ .ok_or(DecompressError::Ascii85("group value out of range"))?;
+ }
+
+ let bytes = buffer.to_be_bytes();
+ output.extend_from_slice(&bytes[..count - 1]);
+ }
+
+ Ok(output)
+ }
+
+ /// ASCIIHexDecode (PDF 32000-1:2008, 7.4.2): each byte is two hexadecimal
+ /// digits, ASCII whitespace is ignored, and `>` ends the data. A final odd
+ /// digit is treated as if followed by `0`; any other non-hex byte is an error.
+ fn decode_ascii_hex(input: &[u8], limit: Option<usize>) -> Result<Vec<u8>> {
+ let mut output = vec![];
+ let mut high: Option<u8> = None;
+ for &ch in input {
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ if ch == b'>' {
+ break;
+ }
+ if ch.is_ascii_whitespace() {
+ continue;
+ }
+ let nibble = (ch as char)
+ .to_digit(16)
+ .ok_or(DecompressError::AsciiHex("invalid hexadecimal character"))? as u8;
+ match high.take() {
+ Some(h) => output.push((h << 4) | nibble),
+ None => high = Some(nibble),
+ }
+ }
+ if let Some(h) = high {
+ output.push(h << 4);
+ }
+ Ok(output)
+ }
+
+ /// RunLengthDecode (PDF 32000-1:2008, 7.4.5): a length byte `l` where
+ /// `0..=127` copies the next `l + 1` bytes literally, `129..=255` repeats the
+ /// next byte `257 - l` times, and `128` marks the end of data. A stream that
+ /// ends mid-run is decoded best-effort rather than treated as fatal.
+ fn decode_run_length(input: &[u8], limit: Option<usize>) -> Result<Vec<u8>> {
+ let mut output = vec![];
+ let mut i = 0;
+ while i < input.len() {
+ if let Some(max) = limit
+ && output.len() > max
+ {
+ return Err(DecompressError::MemoryLimitExceeded { limit: max }.into());
+ }
+ let length = input[i];
+ i += 1;
+ match length {
+ 128 => break,
+ 0..=127 => {
+ let end = (i + length as usize + 1).min(input.len());
+ output.extend_from_slice(&input[i..end]);
+ i = end;
+ }
+ _ => {
+ let Some(&byte) = input.get(i) else { break };
+ output.resize(output.len() + (257 - length as usize), byte);
+ i += 1;
+ }
+ }
+ }
+ Ok(output)
+ }
+
+ fn decompress_predictor(mut data: Vec<u8>, params: Option<&Dictionary>) -> Result<Vec<u8>> {
+ use crate::filters::png;
+
+ if let Some(params) = params {
+ let predictor = params.get(b"Predictor").and_then(Object::as_i64).unwrap_or(1);
+ if predictor == 2 {
+ // TIFF Predictor 2 (horizontal differencing). Distinct from the PNG
+ // predictors below and previously ignored, so `/Predictor 2` streams
+ // silently decoded to the un-differenced (wrong) bytes.
+ let columns = max(1, params.get(b"Columns").and_then(Object::as_i64).unwrap_or(1)) as usize;
+ let colors = max(1, params.get(b"Colors").and_then(Object::as_i64).unwrap_or(1)) as usize;
+ let bits = max(1, params.get(b"BitsPerComponent").and_then(Object::as_i64).unwrap_or(8)) as usize;
+ data = Self::reverse_tiff_predictor2(data, columns, colors, bits)?;
+ } else if (10..=15).contains(&predictor) {
+ // PNG predictors 10-15. Rows are packed to a byte boundary, so a
+ // sub-byte component depth still occupies ceil(Columns*Colors*bits/8)
+ // bytes per row; the old max(8, bits) width over-read and failed on
+ // valid 1/2/4-bit images. The filter's left reference is whole bytes,
+ // rounded up to one.
+ let columns = max(1, params.get(b"Columns").and_then(Object::as_i64).unwrap_or(1)) as usize;
+ let colors = max(1, params.get(b"Colors").and_then(Object::as_i64).unwrap_or(1)) as usize;
+ let bits = max(1, params.get(b"BitsPerComponent").and_then(Object::as_i64).unwrap_or(8)) as usize;
+ // PrintCraft patch: saturating, so absurd parameters cannot overflow.
+ let bytes_per_row = columns.saturating_mul(colors).saturating_mul(bits).div_ceil(8);
+ let bpp = colors.saturating_mul(bits).div_ceil(8);
+ data = png::decode_frame(data.as_slice(), bpp, bytes_per_row)?;
+ }
+ Ok(data)
+ } else {
+ Ok(data)
+ }
+ }
+
+ /// Reverse TIFF Predictor 2 (horizontal differencing): each sample is the
+ /// running sum of the encoded differences of the same colour component along
+ /// its row (PDF 32000-1:2008 Table 10). Rows are `Columns * Colors` samples of
+ /// `BitsPerComponent` bits; sums wrap modulo `2^BitsPerComponent`. The 1-, 2-,
+ /// 4-, 8- and 16-bit depths PDF allows are all supported; sub-byte samples are
+ /// unpacked, summed and repacked (see [`reverse_tiff_predictor2_subbyte`]).
+ fn reverse_tiff_predictor2(mut data: Vec<u8>, columns: usize, colors: usize, bits: usize) -> Result<Vec<u8>> {
+ match bits {
+ 8 => {
+ let stride = columns.saturating_mul(colors); // PrintCraft patch: saturating
+ if stride > 0 {
+ for row in data.chunks_mut(stride) {
+ for i in colors..row.len() {
+ row[i] = row[i].wrapping_add(row[i - colors]);
+ }
+ }
+ }
+ }
+ 16 => {
+ let stride = columns.saturating_mul(colors).saturating_mul(2); // PrintCraft patch: saturating
+ if stride > 0 {
+ for row in data.chunks_mut(stride) {
+ let samples = row.len() / 2;
+ for s in colors..samples {
+ let prev = u16::from_be_bytes([row[(s - colors) * 2], row[(s - colors) * 2 + 1]]);
+ let cur = u16::from_be_bytes([row[s * 2], row[s * 2 + 1]]);
+ row[s * 2..s * 2 + 2].copy_from_slice(&cur.wrapping_add(prev).to_be_bytes());
+ }
+ }
+ }
+ }
+ 1 | 2 | 4 => {
+ let stride = (columns * colors * bits).div_ceil(8);
+ if stride > 0 {
+ for row in data.chunks_mut(stride) {
+ Self::reverse_tiff_predictor2_subbyte(row, columns, colors, bits);
+ }
+ }
+ }
+ _ => {
+ return Err(DecompressError::Predictor(
+ "TIFF Predictor 2 supports only 1-, 2-, 4-, 8- or 16-bit components",
+ )
+ .into());
+ }
+ }
+ Ok(data)
+ }
+
+ /// Reverse TIFF Predictor 2 for one sub-byte (1/2/4-bit) packed row in place.
+ /// Samples are unpacked MSB-first, summed per colour component modulo
+ /// `2^bits`, then repacked MSB-first; the row's trailing padding bits are kept.
+ fn reverse_tiff_predictor2_subbyte(row: &mut [u8], columns: usize, colors: usize, bits: usize) {
+ let mask = (1u16 << bits) - 1;
+ let samples = columns.saturating_mul(colors).min(row.len() * 8 / bits); // PrintCraft patch: saturating
+ let mut acc = vec![0u16; colors];
+ let mut out = vec![0u8; row.len()];
+ let mut in_bit = 0usize;
+ let mut out_buf = 0u32;
+ let mut out_bits = 0u32;
+ let mut out_idx = 0usize;
+ for s in 0..samples {
+ let byte = in_bit / 8;
+ let off = (in_bit % 8) as u32;
+ let window = ((row[byte] as u16) << 8) | *row.get(byte + 1).unwrap_or(&0) as u16;
+ let sample = (window >> (16 - off - bits as u32)) & mask;
+ in_bit += bits;
+
+ let c = s % colors;
+ acc[c] = (acc[c] + sample) & mask;
+
+ out_buf = (out_buf << bits) | acc[c] as u32;
+ out_bits += bits as u32;
+ if out_bits >= 8 {
+ out[out_idx] = (out_buf >> (out_bits - 8)) as u8;
+ out_idx += 1;
+ out_bits -= 8;
+ }
+ }
+ if out_bits > 0 && out_idx < out.len() {
+ let keep = 8 - out_bits;
+ out[out_idx] = ((out_buf << keep) as u8) | (row[out_idx] & ((1u8 << keep) - 1));
+ }
+ row.copy_from_slice(&out);
+ }
+
+ pub fn decompress(&mut self) -> Result<()> {
+ let data = self.decompressed_content()?;
+ self.dict.remove(b"DecodeParms");
+ self.dict.remove(b"Filter");
+ self.set_content(data);
+ Ok(())
+ }
+
+ /// Decompress this stream in place like [`Stream::decompress`], but reject it
+ /// with [`DecompressError::MemoryLimitExceeded`] if the decoded output would
+ /// exceed `max_output` bytes. Used on the load path to bound the memory a
+ /// single object/xref stream can consume.
+ pub fn decompress_with_limit(&mut self, max_output: usize) -> Result<()> {
+ let data = self.decompressed_content_with_limit(max_output)?;
+ self.dict.remove(b"DecodeParms");
+ self.dict.remove(b"Filter");
+ self.set_content(data);
+ Ok(())
+ }
+
+ pub fn is_compressed(&self) -> bool {
+ self.dict.get(b"Filter").is_ok()
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use crate::{Error, error::DecompressError};
+
+ use super::Stream;
+
+ #[test]
+ fn test_decode_ascii85() {
+ let input = r#"9jqo^BlbD-BleB1DJ+*+F(f,q/0JhKF<GL>[email protected]$d7F!,L7@<6@)/0JDEF<G%<+EV:2F!,O<
+ DJ+*.@<*K0@<6L(Df-\0Ec5e;DffZ(EZee.Bl.9pF"AGXBPCsi+DGm>@3BB/F*&OCAfu2/AKYi(
+ DIb:@FD,*)+C]U=@3BN#EcYf8ATD3s@q?d$AftVqCh[NqF<G:8+EV:.+Cf>-FD5W8ARlolDIal(
+ DId<j@<?3r@:F%a+D58'ATD4$Bl@l3De:,-DJs`8ARoFb/0JMK@qB4^F!,R<AKZ&-DfTqBG%G>u
+ D.RTpAKYo'+CT/5+Cei#DII?(E,9)oF*2M7/c~>"#;
+ let expected = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
+ let output = Stream::decode_ascii85(input.as_bytes(), None).unwrap();
+ println!("{}", String::from_utf8(output.clone()).unwrap());
+ assert_eq!(&output, expected.as_bytes());
+ }
+
+ #[test]
+ fn test_decode_ascii85_overflow() {
+ let input = b"uuuuu~>";
+ let output = Stream::decode_ascii85(input, None);
+ // let expected: Result<Vec<u8>, Error> = Err(Error::ContentDecode);
+ assert!(matches!(output, Err(Error::Decompress(DecompressError::Ascii85(_)))));
+ }
+
+ #[test]
+ fn test_decode_ascii85_group_value_out_of_range() {
+ // A base-85 group must be < 2^32. 85 * 50529027 == u32::MAX, so the prefix
+ // "s8W-" reaches the multiply ceiling and the 5th digit overflows the add;
+ // the multiply-only guard missed this. The value == u32::MAX case ("s8W-!")
+ // is in range and must still decode.
+ assert_eq!(
+ Stream::decode_ascii85(b"s8W-!~>", None).unwrap(),
+ vec![255, 255, 255, 255]
+ );
+
+ for input in [
+ &b"s8W-\"~>"[..], // value == 2^32 (issue #442)
+ &b"s8W-~>"[..], // same overflow via the partial-group padding
+ &b"uuuuu~>"[..], // overflow caught by the multiply
+ ] {
+ let out = Stream::decode_ascii85(input, None);
+ assert!(
+ matches!(out, Err(Error::Decompress(DecompressError::Ascii85(_)))),
+ "expected {input:?} to be rejected, got {out:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_decode_ascii85_valid_vectors() {
+ let cases: &[(&[u8], &[u8])] = &[
+ (b"88/~>", &[72, 105]),
+ (b"87cURD_*#4DfTZ)+T~>", b"Hello, World!"),
+ (b"z~>", &[0, 0, 0, 0]),
+ (b":ddb~>", b"PDF"),
+ (
+ b"!!*-'\"9eu7#RLhG$k3[W&.oNg~>",
+ &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
+ ),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ &Stream::decode_ascii85(input, None).unwrap(),
+ expected,
+ "input {input:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_decompress_tiff_predictor2() {
+ use crate::Dictionary;
+
+ fn params(colors: i64, columns: i64, bits: i64) -> Dictionary {
+ let mut p = Dictionary::new();
+ p.set("Predictor", 2i64);
+ p.set("Colors", colors);
+ p.set("Columns", columns);
+ p.set("BitsPerComponent", bits);
+ p
+ }
+
+ // 8-bit single component: running sum along the row, wrapping mod 256.
+ assert_eq!(
+ Stream::decompress_predictor(vec![10, 5, 250, 1], Some(&params(1, 4, 8))).unwrap(),
+ vec![10, 15, 9, 10]
+ );
+ // 8-bit, 3 colours: differencing is per component.
+ assert_eq!(
+ Stream::decompress_predictor(vec![255, 0, 128, 1, 2, 3], Some(&params(3, 2, 8))).unwrap(),
+ vec![255, 0, 128, 0, 2, 131]
+ );
+ // 8-bit: rows reconstruct independently.
+ assert_eq!(
+ Stream::decompress_predictor(vec![1, 2, 3, 10, 20, 30], Some(&params(1, 3, 8))).unwrap(),
+ vec![1, 3, 6, 10, 30, 60]
+ );
+ // 16-bit big-endian samples, sums wrap mod 2^16.
+ assert_eq!(
+ Stream::decompress_predictor(vec![0xFF, 0xFF, 0x00, 0x02], Some(&params(1, 2, 16))).unwrap(),
+ vec![0xFF, 0xFF, 0x00, 0x01]
+ );
+ // Sub-byte depths (1/2/4-bit) are now reconstructed instead of rejected;
+ // values verified against pdf.js. 1-bit, 8 columns: running sum mod 2.
+ assert_eq!(
+ Stream::decompress_predictor(vec![0b1010_1010], Some(&params(1, 8, 1))).unwrap(),
+ vec![0b1100_1100]
+ );
+ // 1-bit, 16 columns, two rows.
+ assert_eq!(
+ Stream::decompress_predictor(vec![255, 170, 8, 255], Some(&params(1, 16, 1))).unwrap(),
+ vec![170, 204, 15, 85]
+ );
+ // 2-bit and 4-bit, single component (rows have trailing padding bits).
+ assert_eq!(
+ Stream::decompress_predictor(vec![85, 179], Some(&params(1, 6, 2))).unwrap(),
+ vec![108, 147]
+ );
+ assert_eq!(
+ Stream::decompress_predictor(vec![25, 16], Some(&params(1, 3, 4))).unwrap(),
+ vec![26, 176]
+ );
+ // 4-bit, 2 colours: differencing stays per component.
+ assert_eq!(
+ Stream::decompress_predictor(vec![18, 34], Some(&params(2, 2, 4))).unwrap(),
+ vec![18, 52]
+ );
+ // A depth PDF never uses (not 1/2/4/8/16) is still rejected.
+ assert!(matches!(
+ Stream::decompress_predictor(vec![0, 0, 0], Some(&params(1, 4, 3))),
+ Err(Error::Decompress(DecompressError::Predictor(_)))
+ ));
+ }
+
+ #[test]
+ fn test_decompress_png_predictor_subbyte() {
+ use crate::Dictionary;
+
+ // Predictor 15 (PNG). Each row carries a leading filter-type byte. Decoded
+ // bytes verified against pdf.js and a real libpng-encoded 1-bit PNG.
+ fn params(colors: i64, columns: i64, bits: i64) -> Dictionary {
+ let mut p = Dictionary::new();
+ p.set("Predictor", 15i64);
+ p.set("Colors", colors);
+ p.set("Columns", columns);
+ p.set("BitsPerComponent", bits);
+ p
+ }
+
+ // 1-bit grayscale, 16 columns: 2 packed bytes/row. Before the fix this
+ // decoded with a 16-byte row width and failed with UnexpectedEof on a
+ // valid image. Filters None/Sub/Up.
+ assert_eq!(
+ Stream::decompress_predictor(vec![0, 170, 204, 1, 15, 70, 2, 225, 65], Some(&params(1, 16, 1))).unwrap(),
+ vec![170, 204, 15, 85, 240, 150]
+ );
+ // 2-bit grayscale, 6 columns (Sub, Average).
+ assert_eq!(
+ Stream::decompress_predictor(vec![1, 108, 36, 3, 144, 141], Some(&params(1, 6, 2))).unwrap(),
+ vec![108, 144, 198, 56]
+ );
+ // 4-bit grayscale, 3 columns (Up, Paeth).
+ assert_eq!(
+ Stream::decompress_predictor(vec![2, 26, 176, 4, 171, 107], Some(&params(1, 3, 4))).unwrap(),
+ vec![26, 176, 197, 48]
+ );
+ // 2-bit RGB (3 colours), 4 columns: 3 bytes/row, left reference = 1 byte.
+ // The old bytes_per_pixel * pixels_per_row factorisation could not express
+ // this row width.
+ assert_eq!(
+ Stream::decompress_predictor(vec![1, 108, 48, 72, 4, 175, 202, 241], Some(&params(3, 4, 2))).unwrap(),
+ vec![108, 156, 228, 27, 54, 141]
+ );
+ }
+
+ #[test]
+ fn test_decompress_zlib_corrupt_checksum() {
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+ use std::io::Write;
+
+ let original = b"BT /F1 12 Tf (Hello World) Tj ET";
+
+ // Compress with valid zlib
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(original).unwrap();
+ let mut compressed = encoder.finish().unwrap();
+
+ // Corrupt the adler32 checksum (last 4 bytes)
+ let len = compressed.len();
+ assert!(len >= 4);
+ for byte in &mut compressed[len - 4..] {
+ *byte ^= 0xFF;
+ }
+
+ // Normal zlib should fail, but our fallback should recover
+ let result = Stream::decompress_zlib(&compressed, None, None).unwrap();
+ assert_eq!(result, original);
+ }
+
+ #[test]
+ fn test_uncompressed_stream_returns_raw_content() {
+ use crate::Dictionary;
+
+ // A stream with no /Filter should return its raw content from decompressed_content()
+ let content = b"/FullPage Do
+"
+ .to_vec();
+ let mut dict = Dictionary::new();
+ dict.set("Length", content.len() as i64);
+ let stream = Stream::new(dict, content.clone());
+
+ let result = stream
+ .decompressed_content()
+ .expect("should succeed for uncompressed stream");
+ assert_eq!(result, content);
+ }
+
+ #[test]
+ fn test_uncompressed_stream_honors_limit() {
+ use crate::Dictionary;
+
+ // Even with no filter, an over-limit raw stream must be rejected so the
+ // caller's memory bound is never silently exceeded.
+ let content = vec![0u8; 1024];
+ let mut dict = Dictionary::new();
+ dict.set("Length", content.len() as i64);
+ let stream = Stream::new(dict, content);
+
+ assert!(matches!(
+ stream.decompressed_content_with_limit(512),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit: 512 }))
+ ));
+ assert!(stream.decompressed_content_with_limit(4096).is_ok());
+ }
+
+ #[test]
+ fn test_limited_writer_fills_to_limit_then_errors() {
+ use super::LimitedWriter;
+ use std::io::Write;
+
+ // The push-based (LZW) guard: the sink accepts bytes up to `limit`, then
+ // fills the remaining room and refuses further writes, so the caller can
+ // detect the overflow via `len() > max` without unbounded allocation.
+ let mut buf = Vec::new();
+ let mut writer = LimitedWriter::new(&mut buf, 4);
+
+ assert_eq!(writer.write(b"ab").unwrap(), 2);
+ // This write would cross the limit: it fills to exactly 4 bytes, errors.
+ let err = writer.write(b"cdef").unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::WriteZero);
+
+ assert_eq!(buf, b"abcd");
+ }
+
+ #[test]
+ fn test_ascii85_honors_limit() {
+ // Each `z` expands to four zero bytes, so 1 MiB of `z` decodes to 4 MiB.
+ // Without a limit that full 4x amplification is allocated; with a limit
+ // the decoder must stop rather than expand past it (guards the chained
+ // `[FlateDecode ASCII85Decode]` bomb vector on the load path).
+ let mut input = vec![b'z'; 1024 * 1024];
+ input.extend_from_slice(b"~>");
+
+ let full = Stream::decode_ascii85(&input, None).unwrap();
+ assert_eq!(full.len(), 4 * 1024 * 1024, "unbounded ASCII85 amplifies 4x");
+
+ assert!(matches!(
+ Stream::decode_ascii85(&input, Some(1024 * 1024)),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) if limit == 1024 * 1024
+ ));
+ }
+
+ #[test]
+ fn test_lzw_bomb_rejected_with_limit() {
+ use crate::Dictionary;
+ use weezl::{BitOrder, encode::Encoder};
+
+ // A tiny LZW stream that decodes back to 8 MiB of zeros. The encoder must
+ // match lopdf's default decoder (`with_tiff_size_switch`, code size 8).
+ let plain = vec![0u8; 8 * 1024 * 1024];
+ let compressed = Encoder::with_tiff_size_switch(BitOrder::Msb, 8).encode(&plain).unwrap();
+ assert!(compressed.len() < 128 * 1024, "LZW bomb input should be tiny");
+
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "LZWDecode");
+ let stream = Stream::new(dict, compressed);
+
+ // Bounded: the push-based LZW path (LimitedWriter + weezl) rejects it.
+ assert!(matches!(
+ stream.decompressed_content_with_limit(1024 * 1024),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) if limit == 1024 * 1024
+ ));
+ // Unbounded default still round-trips fully (proves the pairing is valid,
+ // so the rejection above is real and not a decode failure).
+ assert_eq!(stream.decompressed_content().unwrap().len(), 8 * 1024 * 1024);
+ }
+
+ #[test]
+ fn test_decode_ascii_hex() {
+ use crate::Dictionary;
+
+ // Whole-stream path: a `/Filter /ASCIIHexDecode` stream decodes to bytes.
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "ASCIIHexDecode");
+ let stream = Stream::new(dict, b"48656C6C6F>".to_vec());
+ assert_eq!(stream.decompressed_content().unwrap(), b"Hello");
+
+ // Spec vectors (PDF 32000-1 7.4.2). Whitespace is ignored, `>` ends the
+ // data, and a trailing odd digit is padded with 0.
+ let cases: &[(&[u8], &[u8])] = &[
+ (b"48 65 6C\n6C6F>", b"Hello"),
+ (b"901FA3>", &[0x90, 0x1F, 0xA3]),
+ (b"4A5>", &[0x4A, 0x50]),
+ (b"4>", &[0x40]),
+ (b">", &[]),
+ (b"4865>ffff", b"He"),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ &Stream::decode_ascii_hex(input, None).unwrap(),
+ expected,
+ "input {input:?}"
+ );
+ }
+
+ // A byte that is neither a hex digit, whitespace, nor `>` is rejected.
+ assert!(matches!(
+ Stream::decode_ascii_hex(b"48XY>", None),
+ Err(Error::Decompress(DecompressError::AsciiHex(_)))
+ ));
+ }
+
+ #[test]
+ fn test_decode_run_length() {
+ use crate::Dictionary;
+
+ // Whole-stream path: literal run of 5, then 3 copies of 'A', then EOD.
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "RunLengthDecode");
+ let mut data = vec![0x04];
+ data.extend_from_slice(b"Hello");
+ data.extend_from_slice(&[0xFE, b'A', 0x80]);
+ let stream = Stream::new(dict, data);
+ assert_eq!(stream.decompressed_content().unwrap(), b"HelloAAA");
+
+ // Spec vectors (PDF 32000-1 7.4.5). Length 0x81 = 128 copies, 0xFF = 2,
+ // 0x80 = end of data (trailing bytes are dropped), and a run that ends
+ // without an EOD marker is decoded best-effort.
+ let cases: &[(&[u8], Vec<u8>)] = &[
+ (&[0x81, b'Z', 0x80], vec![b'Z'; 128]),
+ (&[0xFF, b'Q', 0x00, b'!', 0x80], b"QQ!".to_vec()),
+ (&[0x02, b'a', b'b', b'c', 0x80, b'x', b'y'], b"abc".to_vec()),
+ (&[0x01, b'H', b'i'], b"Hi".to_vec()),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ &Stream::decode_run_length(input, None).unwrap(),
+ expected,
+ "input {input:?}"
+ );
+ }
+
+ // Run-length can amplify up to 128x, so an over-limit stream must be
+ // rejected instead of allocating the full expansion (bomb guard).
+ let bomb: Vec<u8> = std::iter::repeat_n([0x81u8, b'x'], 4096).flatten().collect();
+ assert_eq!(Stream::decode_run_length(&bomb, None).unwrap().len(), 128 * 4096);
+ assert!(matches!(
+ Stream::decode_run_length(&bomb, Some(64 * 1024)),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) if limit == 64 * 1024
+ ));
+ }
+}
diff --git a/vendor/lopdf/src/object_stream.rs b/vendor/lopdf/src/object_stream.rs
new file mode 100644
index 000000000..8b4c423a9
--- /dev/null
+++ b/vendor/lopdf/src/object_stream.rs
@@ -0,0 +1,348 @@
+use crate::parser;
+use crate::{Document, Error, Object, ObjectId, Result, Stream};
+use std::collections::BTreeMap;
+use std::num::TryFromIntError;
+use std::str::FromStr;
+
+use log::warn;
+#[cfg(feature = "rayon")]
+use rayon::prelude::*;
+
+#[derive(Debug)]
+pub struct ObjectStream {
+ pub objects: BTreeMap<ObjectId, Object>,
+ max_objects: usize,
+ compression_level: u32,
+}
+
+#[derive(Debug, Clone)]
+pub struct ObjectStreamBuilder {
+ max_objects: usize,
+ compression_level: u32,
+}
+
+#[derive(Debug, Clone)]
+pub struct ObjectStreamConfig {
+ pub max_objects_per_stream: usize,
+ pub compression_level: u32,
+}
+
+impl Default for ObjectStreamConfig {
+ fn default() -> Self {
+ Self {
+ max_objects_per_stream: 100,
+ compression_level: 6,
+ }
+ }
+}
+
+impl ObjectStream {
+ /// Parse an existing object stream without modifying its encoded content or
+ /// filter dictionary.
+ ///
+ /// This decodes the stream without any size limit. For untrusted input,
+ /// prefer [`ObjectStream::new_with_limit`] to guard against decompression
+ /// bombs.
+ pub fn new(stream: &Stream) -> Result<ObjectStream> {
+ Self::new_with_limit(stream, None)
+ }
+
+ /// Parse an existing object stream without modifying it, rejecting the
+ /// decoded content if it would exceed `max_decompressed_size` bytes. `None`
+ /// means no limit (the behavior of [`ObjectStream::new`]).
+ pub fn new_with_limit(stream: &Stream, max_decompressed_size: Option<usize>) -> Result<ObjectStream> {
+ let content = match max_decompressed_size {
+ // Object streams are decoded while the document is loaded, so
+ // enforcing the limit here bounds the memory a single stream can use.
+ Some(max) => stream.get_plain_content_with_limit(max)?,
+ None => stream.get_plain_content()?,
+ };
+
+ if content.is_empty() {
+ return Ok(ObjectStream {
+ objects: BTreeMap::new(),
+ max_objects: 100,
+ compression_level: 6,
+ });
+ }
+
+ let first_offset = stream
+ .dict
+ .get(b"First")
+ .and_then(Object::as_i64)?
+ .try_into()
+ .map_err(|e: TryFromIntError| Error::NumericCast(e.to_string()))?;
+ let index_block = content.get(..first_offset).ok_or(Error::InvalidOffset(first_offset))?;
+
+ let numbers_str = std::str::from_utf8(index_block).map_err(|e| Error::InvalidObjectStream(e.to_string()))?;
+ let numbers: Vec<_> = numbers_str
+ .split_whitespace()
+ .map(|number| u32::from_str(number).ok())
+ .collect();
+ let len = numbers.len() / 2 * 2; // Ensure only pairs.
+
+ let n = stream.dict.get(b"N").and_then(Object::as_i64)?;
+ if numbers.len().try_into().ok() != n.checked_mul(2) {
+ warn!("object stream: the object stream dictionary specifies a wrong number of objects")
+ }
+
+ let chunks_filter_map = |chunk: &[_]| {
+ let id = chunk[0]?;
+ let offset = first_offset + chunk[1]? as usize;
+
+ if offset >= content.len() {
+ warn!("out-of-bounds offset in object stream");
+ return None;
+ }
+ // Skip leading whitespace — some PDFs emit newlines before objects in ObjStm
+ let mut start = offset;
+ while start < content.len() && content[start].is_ascii_whitespace() {
+ start += 1;
+ }
+ if start >= content.len() {
+ warn!("only whitespace after offset in object stream");
+ return None;
+ }
+ let object = parser::direct_object(&content[start..])?;
+
+ Some(((id, 0), object))
+ };
+ #[cfg(feature = "rayon")]
+ let objects = numbers[..len].par_chunks(2).filter_map(chunks_filter_map).collect();
+ #[cfg(not(feature = "rayon"))]
+ let objects = numbers[..len].chunks(2).filter_map(chunks_filter_map).collect();
+
+ Ok(ObjectStream {
+ objects,
+ max_objects: 100,
+ compression_level: 6,
+ })
+ }
+
+ /// Create a builder for constructing new object streams
+ pub fn builder() -> ObjectStreamBuilder {
+ ObjectStreamBuilder {
+ max_objects: 100,
+ compression_level: 6,
+ }
+ }
+
+ /// Add an object to the stream
+ pub fn add_object(&mut self, id: ObjectId, obj: Object) -> Result<()> {
+ // Check if object can be added to stream
+ if matches!(obj, Object::Stream(_)) {
+ return Err(Error::InvalidObjectStream(
+ "Stream objects cannot be stored in object streams".into(),
+ ));
+ }
+
+ // Check capacity
+ if self.objects.len() >= self.max_objects {
+ return Err(Error::InvalidObjectStream(format!(
+ "Object stream has reached maximum capacity of {} objects",
+ self.max_objects
+ )));
+ }
+
+ self.objects.insert(id, obj);
+ Ok(())
+ }
+
+ /// Get the number of objects in the stream
+ pub fn object_count(&self) -> usize {
+ self.objects.len()
+ }
+
+ /// Build the stream content in the format required by PDF spec
+ pub fn build_stream_content(&self) -> Result<Vec<u8>> {
+ if self.objects.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // Sort objects by ID for consistent output
+ let mut sorted_objects: Vec<_> = self.objects.iter().collect();
+ sorted_objects.sort_by_key(|(id, _)| *id);
+
+ // First build the offset table to know its size
+ let mut offset_entries = Vec::new();
+ let mut current_offset = 0;
+
+ for ((obj_num, _gen), obj) in &sorted_objects {
+ // Store the object number and its offset
+ offset_entries.push(format!("{obj_num} {current_offset}"));
+
+ // Calculate size of this object's serialization
+ let mut obj_bytes = Vec::new();
+ crate::writer::Writer::write_object(&mut obj_bytes, obj)?;
+ current_offset += obj_bytes.len() + 1; // +1 for space separator
+ }
+
+ // Build the complete offset table with proper spacing
+ let offset_table = offset_entries.join(" ") + " ";
+
+ // Now build the final content
+ let mut content = Vec::new();
+ content.extend_from_slice(offset_table.as_bytes());
+
+ // Add serialized objects with space separators
+ for ((_, _), obj) in &sorted_objects {
+ let mut obj_bytes = Vec::new();
+ crate::writer::Writer::write_object(&mut obj_bytes, obj)?;
+ content.extend_from_slice(&obj_bytes);
+ content.push(b' '); // Space separator between objects
+ }
+
+ Ok(content)
+ }
+
+ /// Convert to a Stream object ready for insertion into a PDF
+ pub fn to_stream_object(&self) -> Result<Stream> {
+ let content = self.build_stream_content()?;
+
+ // Calculate where the first object starts
+ // We need to find the size of the offset table
+ let mut sorted_objects: Vec<_> = self.objects.iter().collect();
+ sorted_objects.sort_by_key(|(id, _)| *id);
+
+ // Build the offset entries to calculate exact size
+ let mut offset_entries = Vec::new();
+ let mut current_offset = 0;
+
+ for ((obj_num, _gen), obj) in &sorted_objects {
+ offset_entries.push(format!("{obj_num} {current_offset}"));
+
+ // Calculate size of this object's serialization
+ let mut obj_bytes = Vec::new();
+ crate::writer::Writer::write_object(&mut obj_bytes, obj)?;
+ current_offset += obj_bytes.len() + 1; // +1 for space separator
+ }
+
+ // The offset table is joined with spaces and has a trailing space
+ let offset_table = offset_entries.join(" ") + " ";
+ let first_offset = offset_table.len();
+
+ let dict = dictionary! {
+ "Type" => "ObjStm",
+ "N" => self.objects.len() as i64,
+ "First" => first_offset as i64,
+ };
+
+ let mut stream = Stream::new(dict, content);
+
+ // Apply compression - object streams should always be compressed
+ if self.compression_level > 0 {
+ // Force compression by setting Filter directly
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+ use std::io::prelude::*;
+
+ let compression = match self.compression_level {
+ 0 => Compression::none(),
+ 1..=3 => Compression::fast(),
+ 4..=6 => Compression::default(),
+ _ => Compression::best(),
+ };
+
+ let mut encoder = ZlibEncoder::new(Vec::new(), compression);
+ encoder.write_all(&stream.content)?;
+ let compressed = encoder.finish()?;
+
+ stream.dict.set("Filter", "FlateDecode");
+ stream.set_content(compressed);
+ }
+
+ Ok(stream)
+ }
+
+ /// Check if an object can be compressed into an object stream
+ pub fn can_be_compressed(id: ObjectId, obj: &Object, doc: &Document) -> bool {
+ // Rule 1: Stream objects cannot be compressed
+ if matches!(obj, Object::Stream(_)) {
+ return false;
+ }
+
+ // Rule 2: Objects with non-zero generation cannot be compressed
+ if id.1 != 0 {
+ return false;
+ }
+
+ // Rule 3: Only encryption dictionary cannot be compressed from trailer references
+ if let Ok(Object::Reference(encrypt_ref)) = doc.trailer.get(b"Encrypt")
+ && id == *encrypt_ref
+ {
+ return false;
+ }
+
+ // Rule 4: Specific object types that cannot be compressed
+ if let Object::Dictionary(dict) = obj
+ && let Ok(type_obj) = dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ {
+ match type_name {
+ // Cross-reference streams and object streams cannot be compressed
+ b"XRef" => return false,
+ b"ObjStm" => return false,
+
+ // Catalog can only be excluded in linearized PDFs
+ b"Catalog" if Self::is_linearized(doc) => {
+ return false;
+ }
+ b"Catalog" => {}
+
+ // Page, Pages, and all other types CAN be compressed
+ _ => {}
+ }
+ }
+
+ // Default: Allow compression
+ true
+ }
+
+ /// Check if a PDF document is linearized
+ fn is_linearized(doc: &Document) -> bool {
+ // In a linearized PDF, the first object after the header should be a
+ // linearization dictionary with /Linearized entry
+ // For simplicity, we check if any object has a /Linearized entry
+ for obj in doc.objects.values() {
+ if let Object::Dictionary(dict) = obj
+ && dict.has(b"Linearized")
+ {
+ return true;
+ }
+ }
+ false
+ }
+}
+
+impl ObjectStreamBuilder {
+ /// Set the maximum number of objects per stream
+ pub fn max_objects(mut self, max: usize) -> Self {
+ self.max_objects = max;
+ self
+ }
+
+ /// Set the compression level (0-9)
+ pub fn compression_level(mut self, level: u32) -> Self {
+ self.compression_level = level;
+ self
+ }
+
+ /// Build the ObjectStream
+ pub fn build(self) -> ObjectStream {
+ ObjectStream {
+ objects: BTreeMap::new(),
+ max_objects: self.max_objects,
+ compression_level: self.compression_level,
+ }
+ }
+
+ /// Get the current max_objects setting
+ pub fn get_max_objects(&self) -> usize {
+ self.max_objects
+ }
+
+ /// Get the current compression_level setting
+ pub fn get_compression_level(&self) -> u32 {
+ self.compression_level
+ }
+}
diff --git a/vendor/lopdf/src/outlines.rs b/vendor/lopdf/src/outlines.rs
new file mode 100644
index 000000000..2a9b581cf
--- /dev/null
+++ b/vendor/lopdf/src/outlines.rs
@@ -0,0 +1,168 @@
+use indexmap::IndexMap;
+
+use super::{Destination, Dictionary, Document, Error, Object, ObjectId, Result};
+
+#[derive(Debug, Clone)]
+pub enum Outline {
+ Destination(Destination),
+ SubOutlines(Vec<Outline>),
+}
+
+impl Document {
+ pub fn get_outline(
+ &self, node: &Dictionary, named_destinations: &mut IndexMap<Vec<u8>, Destination>,
+ ) -> Result<Option<Outline>> {
+ let action = match self.get_dict_in_dict(node, b"A") {
+ Ok(a) => a,
+ Err(_) => {
+ return self.build_outline_result(node.get(b"Dest")?, node.get(b"Title")?, named_destinations);
+ }
+ };
+ let command = action.get(b"S")?.as_name()?;
+ if command != b"GoTo" && command != b"GoToR" {
+ return Err(Error::InvalidOutline("Expected GoTo or GoToR".to_string()));
+ }
+ let title_obj = node.get(b"Title")?;
+ let title_ref = match title_obj.as_reference() {
+ Ok(o) => o,
+ Err(_) => match title_obj.as_str() {
+ Ok(_) => return self.build_outline_result(action.get(b"D")?, title_obj, named_destinations),
+ Err(err) => return Err(err),
+ },
+ };
+ self.build_outline_result(action.get(b"D")?, self.get_object(title_ref)?, named_destinations)
+ }
+
+ pub fn get_outlines(
+ &self, node: Option<Object>, outlines: Option<Vec<Outline>>,
+ named_destinations: &mut IndexMap<Vec<u8>, Destination>,
+ ) -> Result<Option<Vec<Outline>>> {
+ self.get_outlines_impl(node, outlines, named_destinations, 0)
+ }
+
+ fn get_outlines_impl(
+ &self, mut node: Option<Object>, mut outlines: Option<Vec<Outline>>,
+ named_destinations: &mut IndexMap<Vec<u8>, Destination>, depth: usize,
+ ) -> Result<Option<Vec<Outline>>> {
+ if depth >= crate::reader::MAX_NESTING_DEPTH {
+ return Err(Error::RecursionLimit);
+ }
+ if outlines.is_none() {
+ outlines = Some(Vec::new());
+ let catalog = self.catalog()?;
+ let mut dict_node = self.get_dict_in_dict(catalog, b"Outlines")?;
+ let first = self.get_dict_in_dict(dict_node, b"First");
+ if let Ok(first) = first {
+ dict_node = first;
+ }
+ let mut tree = self.get_dict_in_dict(catalog, b"Dests");
+ if tree.is_err() {
+ let names = self.get_dict_in_dict(catalog, b"Names");
+ if let Ok(names) = names {
+ let dests = self.get_dict_in_dict(names, b"Dests");
+ if dests.is_ok() {
+ tree = dests;
+ }
+ }
+ }
+ if let Ok(tree) = tree {
+ self.get_named_destinations(tree, named_destinations)?;
+ }
+ node = Some(Object::Dictionary(dict_node.clone()));
+ }
+ if node.is_none() {
+ return Ok(outlines);
+ }
+ let node = node.unwrap();
+ let mut node = match node.as_dict() {
+ Ok(n) => n,
+ Err(_) => self.get_object(node.as_reference()?)?.as_dict()?,
+ };
+ loop {
+ if let Ok(Some(outline)) = self.get_outline(node, named_destinations)
+ && let Some(ref mut outlines) = outlines
+ {
+ outlines.push(outline);
+ }
+ if let Ok(first) = node.get(b"First") {
+ let sub_outlines = Vec::new();
+ let sub_outlines =
+ self.get_outlines_impl(Some(first.clone()), Some(sub_outlines), named_destinations, depth + 1)?;
+ if let Some(sub_outlines) = sub_outlines
+ && !sub_outlines.is_empty()
+ && let Some(ref mut outlines) = outlines
+ {
+ outlines.push(Outline::SubOutlines(sub_outlines));
+ }
+ }
+ node = match self.get_dict_in_dict(node, b"Next") {
+ Ok(n) => n,
+ Err(_) => break,
+ };
+ }
+ Ok(outlines)
+ }
+
+ pub fn delete_outlines(&mut self) -> Result<()> {
+ if let Some(outlines_id) = self
+ .catalog()?
+ .get(b"Outlines")
+ .ok()
+ .and_then(|v| v.as_reference().ok())
+ {
+ let outlines = self.get_dictionary(outlines_id)?;
+ if let Ok(Object::Reference(first)) = outlines.get(b"First") {
+ self.walk_outlines_del(*first, 0)?;
+ }
+ self.delete_object(outlines_id);
+ }
+
+ Ok(())
+ }
+
+ fn build_outline_result(
+ &self, dest: &Object, title: &Object, named_destinations: &mut IndexMap<Vec<u8>, Destination>,
+ ) -> Result<Option<Outline>> {
+ let outline = match dest {
+ Object::Array(obj_array) => Outline::Destination(Destination::new(
+ title.to_owned(),
+ obj_array[0].clone(),
+ obj_array[1].clone(),
+ )),
+ Object::String(key, _fmt) => {
+ if let Some(destination) = named_destinations.get_mut(key) {
+ destination.set(b"Title", title.to_owned());
+ Outline::Destination(destination.clone())
+ } else {
+ return Ok(None);
+ }
+ }
+ Object::Reference(object_id) => {
+ return self.build_outline_result(self.get_object(*object_id)?, title, named_destinations);
+ }
+ _ => return Err(Error::InvalidOutline(format!("Unexpected destination {dest:?}"))),
+ };
+ Ok(Some(outline))
+ }
+
+ fn walk_outlines_del(&mut self, outline: ObjectId, depth: usize) -> Result<()> {
+ if depth >= crate::reader::MAX_NESTING_DEPTH {
+ return Err(Error::RecursionLimit);
+ }
+ let mut cur = Some(outline);
+
+ while let Some(id) = cur.take() {
+ let outline = self.get_dictionary(id)?;
+ let first = outline.get(b"First").ok().and_then(|v| v.as_reference().ok());
+ let next = outline.get(b"Next").ok().and_then(|v| v.as_reference().ok());
+
+ if let Some(first) = first {
+ self.walk_outlines_del(first, depth + 1)?;
+ }
+ cur = next;
+ self.delete_object(id);
+ }
+
+ Ok(())
+ }
+}
diff --git a/vendor/lopdf/src/parser/cmap_parser.rs b/vendor/lopdf/src/parser/cmap_parser.rs
new file mode 100644
index 000000000..015a23bb1
--- /dev/null
+++ b/vendor/lopdf/src/parser/cmap_parser.rs
@@ -0,0 +1,1163 @@
+use crate::cmap_section::{ArrayOfTargetStrings, CMapParseError, CMapSection, CodeLen, SourceCode, SourceRangeMapping};
+use crate::parser::{NomResult, ParserInput, comment, dict_dup, dictionary, eol, hex_char, name};
+use nom::Parser;
+use nom::branch::alt;
+pub use nom::bytes::complete::tag;
+use nom::combinator::{map, opt};
+use nom::error::ParseError;
+use nom::multi::{fold_many_m_n, fold_many0, fold_many1, many_m_n, many0, many1, separated_list1};
+use nom::sequence::{pair, preceded, separated_pair, terminated};
+use nom::{character::complete::digit1, sequence::delimited};
+
+impl<E> From<nom::Err<E>> for CMapParseError {
+ fn from(err: nom::Err<E>) -> Self {
+ match err {
+ nom::Err::Incomplete(_) => CMapParseError::Incomplete,
+ // normally nom::Err::Error is a recoverable error, but CMapParseError is the return type
+ // so we assume that there are no more parsing branches to check
+ nom::Err::Failure(_) | nom::Err::Error(_) => CMapParseError::Error,
+ }
+ }
+}
+
+pub(crate) fn parse(stream_content: ParserInput) -> Result<Vec<CMapSection>, CMapParseError> {
+ let result = cmap_stream(stream_content);
+ let result = result.map_err(CMapParseError::from)?;
+ Ok(result.1)
+}
+
+fn cmap_stream(input: ParserInput) -> NomResult<Vec<CMapSection>> {
+ delimited(
+ cidinit_procset,
+ cmap_resource_dictionary,
+ (tag(&b"end"[..]), multispace0),
+ )
+ .parse(input)
+}
+
+fn space0(input: ParserInput) -> NomResult<()> {
+ fold_many0(alt((tag(&b" "[..]), tag("\t"))), || {}, |_, _| ()).parse(input)
+}
+
+fn space1(input: ParserInput) -> NomResult<()> {
+ fold_many1(alt((tag(&b" "[..]), tag("\t"))), || {}, |_, _| ()).parse(input)
+}
+
+fn multispace0(input: ParserInput) -> NomResult<()> {
+ let space = tag(&b" "[..]).map(|_| ());
+ let tab = tag("\t").map(|_| ());
+ let eol = eol.map(|_| ());
+ fold_many0(alt((space, tab, eol, comment)), || {}, |_, _| ()).parse(input)
+}
+
+fn multispace1(input: ParserInput) -> NomResult<()> {
+ let space = tag(&b" "[..]).map(|_| ());
+ let tab = tag("\t").map(|_| ());
+ let eol = eol.map(|_| ());
+ fold_many1(alt((space, tab, eol, comment)), || {}, |_, _| ()).parse(input)
+}
+
+fn cidinit_procset(input: ParserInput) -> NomResult<()> {
+ (
+ opt(tag("\u{FEFF}".as_bytes())),
+ multispace0,
+ tag(&b"/CIDInit"[..]),
+ space0,
+ alt((tag(&b"/ProcSet"[..]), tag(&b"/Procset"[..]))),
+ space1,
+ tag(&b"findresource"[..]),
+ space1,
+ tag(&b"begin"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn cmap_resource_dictionary(input: ParserInput) -> NomResult<Vec<CMapSection>> {
+ let begin_parser = (
+ digit1,
+ space1,
+ tag(&b"dict"[..]),
+ space1,
+ tag(&b"begin"[..]),
+ multispace1,
+ );
+ let end_parser = (tag(&b"end"[..]), multispace1);
+ delimited(begin_parser, cmap_data, end_parser).parse(input)
+}
+
+fn cmap_data(input: ParserInput) -> NomResult<Vec<CMapSection>> {
+ let cmap_end = (
+ tag(&b"endcmap"[..]),
+ multispace1,
+ tag(&b"CMapName"[..]),
+ space1,
+ tag(&b"currentdict"[..]),
+ space1,
+ tag(&b"/CMap"[..]),
+ space1,
+ tag(&b"defineresource"[..]),
+ space1,
+ tag(&b"pop"[..]),
+ multispace1,
+ );
+ delimited(
+ (tag(&b"begincmap"[..]), multispace1),
+ preceded(cmap_metadata, cmap_codespace_and_mappings),
+ cmap_end,
+ )
+ .parse(input)
+}
+
+fn cmap_metadata(input: ParserInput) -> NomResult<()> {
+ let metadata_parser = alt((
+ cid_system_info,
+ cmap_name,
+ cmap_type,
+ cmap_version,
+ uidoffset,
+ wmode,
+ xuid,
+ ));
+ fold_many_m_n(1, 7, metadata_parser, || (), |_, _| ()).parse(input)
+}
+
+fn cid_system_info(input: ParserInput) -> NomResult<()> {
+ // Note: Can array of CIDSystemInfo occur here?
+ // Normally in cmap this can be an array, but can it be also if this is a ToUnicode cmap?
+ (
+ tag(&b"/CIDSystemInfo"[..]),
+ multispace0,
+ alt((dictionary, dict_dup)),
+ multispace1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn cmap_name(input: ParserInput) -> NomResult<()> {
+ (
+ tag(&b"/CMapName"[..]),
+ space0,
+ name,
+ space1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn cmap_type(input: ParserInput) -> NomResult<()> {
+ (
+ tag(&b"/CMapType"[..]),
+ space1,
+ digit1,
+ space1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn cmap_version(input: ParserInput) -> NomResult<()> {
+ let version = (digit1, opt((tag(&b"."[..]), digit1)));
+ (
+ tag(&b"/CMapVersion"[..]),
+ space1,
+ version,
+ space1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn wmode(input: ParserInput) -> NomResult<()> {
+ (
+ tag(&b"/WMode"[..]),
+ space1,
+ digit1,
+ space1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn uidoffset(input: ParserInput) -> NomResult<()> {
+ (
+ tag(&b"/UIDOffset"[..]),
+ space1,
+ digit1,
+ space1,
+ tag(&b"def"[..]),
+ multispace1,
+ )
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn xuid(input: ParserInput) -> NomResult<()> {
+ let array = (tag(&b"["[..]), separated_list1(space1, digit1), tag(&b"]"[..]));
+ (tag(&b"/XUID"[..]), space1, array, space1, tag(&b"def"[..]), multispace1)
+ .parse(input)
+ .map(|(i, _)| (i, ()))
+}
+
+fn cmap_codespace_and_mappings(input: ParserInput) -> NomResult<Vec<CMapSection>> {
+ many1(alt((codespace_range_section, bf_char_section, bf_range_section))).parse(input)
+}
+
+fn codespace_range_section(input: ParserInput) -> NomResult<CMapSection> {
+ let begin_section = (digit1, space1, tag(&b"begincodespacerange"[..]), multispace1);
+ let end_section = (tag(&b"endcodespacerange"[..]), multispace1);
+ let parse_range = delimited(space0, code_range_pair, multispace1);
+ let (rest_of_input, ranges_result) = delimited(begin_section, many1(parse_range), end_section).parse(input)?;
+ Ok((rest_of_input, CMapSection::CsRange(ranges_result)))
+}
+
+fn code_range_pair(input: ParserInput) -> NomResult<(SourceCode, SourceCode, CodeLen)> {
+ let (rest_of_input, ((code_begin, code_len_beg), (code_end, code_len_end))) =
+ separated_pair(source_code, space0, source_code).parse(input)?;
+ if code_len_beg != code_len_end {
+ create_code_len_err(rest_of_input)
+ } else {
+ Ok((rest_of_input, (code_begin, code_end, code_len_beg)))
+ }
+}
+
+fn create_code_len_err<'a, T, E: ParseError<ParserInput<'a>>>(input: ParserInput<'a>) -> Result<T, nom::Err<E>> {
+ Err(nom::Err::Failure(nom::error::make_error(
+ input,
+ nom::error::ErrorKind::LengthValue,
+ )))
+}
+
+fn source_code(input: ParserInput) -> NomResult<(SourceCode, CodeLen)> {
+ let (rest_of_input, bytes) = delimited(tag(&b"<"[..]), many_m_n(1, 4, hex_char), tag(&b">"[..])).parse(input)?;
+ let code_len = bytes.len();
+ let source_code = bytes
+ .into_iter()
+ .rev()
+ .zip(0..4)
+ .map(|(byte, i)| 256u32.pow(i) * byte as u32)
+ .sum();
+ Ok((rest_of_input, (source_code, code_len as u8)))
+}
+
+fn hex_u16(input: ParserInput) -> NomResult<u16> {
+ map(pair(hex_char, hex_char), |(h1, h2)| h1 as u16 * 256 + h2 as u16).parse(input)
+}
+
+fn bf_char_section(input: ParserInput) -> NomResult<CMapSection> {
+ let begin_section = (digit1, space1, tag(&b"beginbfchar"[..]), multispace1);
+ let end_section = (tag(&b"endbfchar"[..]), multispace1);
+ let bf_char_line = delimited(space0, separated_pair(source_code, space0, target_string), multispace1);
+ // Some real-world ToUnicode CMaps contain sections like `0 beginbfchar ... endbfchar`.
+ // Accept empty sections to avoid failing extraction (specifically calling extract_text)
+ let (rest_of_input, bf_char_mappings) = delimited(begin_section, many0(bf_char_line), end_section).parse(input)?;
+ Ok((rest_of_input, CMapSection::BfChar(bf_char_mappings)))
+}
+
+fn target_string(input: ParserInput) -> NomResult<Vec<u16>> {
+ // according to specification dstString can be up to 512 bytes
+ // in ToUnicode cmap these should be 2-byte big endian Unicode values
+ delimited(
+ tag(&b"<"[..]),
+ many_m_n(1, 256, terminated(hex_u16, multispace0)),
+ tag(&b">"[..]),
+ )
+ .parse(input)
+}
+
+fn bf_range_section(input: ParserInput) -> NomResult<CMapSection> {
+ let begin_section = (digit1, space1, tag(&b"beginbfrange"[..]), multispace1);
+ let end_section = (tag(&b"endbfrange"[..]), multispace1);
+ // Some real-world ToUnicode CMaps contain sections like `0 beginbfrange ... endbfrange`.
+ // Accept empty sections to avoid failing extraction (specifically calling extract_text)
+ let (rest_of_input, bf_range_mappings) =
+ delimited(begin_section, many0(bf_range_line), end_section).parse(input)?;
+ Ok((rest_of_input, CMapSection::BfRange(bf_range_mappings)))
+}
+
+fn bf_range_line(input: ParserInput) -> NomResult<SourceRangeMapping> {
+ let bf_range_parser = separated_pair(
+ code_range_pair,
+ space0,
+ alt((target_string.map(|res| vec![res]), range_target_array)),
+ );
+ delimited(space0, bf_range_parser, multispace1).parse(input)
+}
+
+fn range_target_array(input: ParserInput) -> NomResult<ArrayOfTargetStrings> {
+ delimited(
+ (tag(&b"["[..]), space0),
+ separated_list1(space1, target_string),
+ (space0, tag(&b"]"[..])),
+ )
+ .parse(input)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_span(s: &'_ [u8]) -> ParserInput<'_> {
+ s
+ }
+ #[test]
+ fn parse_1byte_source_code() {
+ let data = b"<0A>";
+ let (rem, res) = source_code(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, (0x0a, 1));
+ }
+
+ #[test]
+ fn parse_source_code() {
+ let data = b"<080F>";
+ let (rem, res) = source_code(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, (0x080f, 2));
+ }
+
+ #[test]
+ fn parse_invalid_source_code() {
+ let data = b"<080g01>";
+ assert!(source_code(test_span(data)).is_err())
+ }
+
+ #[test]
+ fn parse_too_long_source_code() {
+ let data = b"<080g01030a>";
+ assert!(source_code(test_span(data)).is_err())
+ }
+
+ #[test]
+ fn parse_code_range_pair() {
+ let data = b"<080F> <08FF> ";
+ let (rem, res) = code_range_pair(test_span(data)).unwrap();
+ assert_eq!(rem, b" ");
+ assert_eq!(res, (0x080f, 0x08ff, 2));
+ }
+
+ #[test]
+ fn parse_code_range_pair_without_spaces() {
+ let data = b"<080F><08FF>";
+
+ let (rem, res) = code_range_pair(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, (0x080f, 0x08ff, 2));
+ }
+
+ #[test]
+ fn parse_code_range_pair_with_not_matching_len() {
+ let data = b"<080F> <08>";
+ assert!(code_range_pair(test_span(data)).is_err())
+ }
+
+ #[test]
+ fn parse_bfrange_line() {
+ let data = b"<080f> <08ff> <09000110>\n";
+ let (rem, res) = bf_range_line(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, ((0x080f, 0x08ff, 2), vec![vec![0x0900, 0x0110]]));
+ }
+ #[test]
+ fn parse_bfrange_line_without_spaces() {
+ let data = b"<080f><08ff><09000110>\n";
+ let (rem, res) = bf_range_line(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, ((0x080f, 0x08ff, 2), vec![vec![0x0900, 0x0110]]));
+ }
+
+ #[test]
+ fn parse_bfrange_line_array() {
+ let data = b"<080f> <08ff> [ <09000110> <08fe> ] \n";
+ let (rem, res) = bf_range_line(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, ((0x080f, 0x08ff, 2), vec![vec![0x0900, 0x0110], vec![0x08fe]]));
+ }
+ #[test]
+ fn parse_invalid_bfrange_line() {
+ let data = b"<080f> <08ff> [ <09000110> <08FF> <09fe80> ]\n";
+ assert!(bf_range_line(test_span(data)).is_err())
+ }
+
+ #[test]
+ fn parse_codespace_range_section() {
+ let data = b"1 begincodespacerange\n\
+ <0000> <FFFF> \n\
+ endcodespacerange\n";
+ let (rem, res) = codespace_range_section(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(res, CMapSection::CsRange(vec![(0x0000, 0xffff, 2)]));
+ }
+
+ #[test]
+ fn parse_bf_range_section() {
+ let data = b"3 beginbfrange \n\
+ <0000> <000f> <0000>\n\
+ <0010> <001f> <00000010> \n\
+ <0020> <002f> [<0000> <00000010> ]\n\
+ endbfrange\n";
+
+ let (rem, res) = bf_range_section(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(
+ res,
+ CMapSection::BfRange(vec![
+ ((0x0000, 0x000f, 2), vec![vec![0x0000]]),
+ ((0x0010, 0x001f, 2), vec![vec![0x0000, 0x0010]]),
+ ((0x0020, 0x002f, 2), vec![vec![0x0000], vec![0x0000, 0x0010]]),
+ ])
+ );
+ }
+
+ #[test]
+ fn parse_bf_char_section() {
+ let data = b"4 beginbfchar \n\
+ <1d> <0066 0069>\n\
+ <1e> <00A0>\n\
+ <1f> <0066 0066>
+ <20> <0020>\n\
+ endbfchar\n";
+ let (rem, res) = bf_char_section(test_span(data)).unwrap();
+ assert_eq!(rem, b"");
+ assert_eq!(
+ res,
+ CMapSection::BfChar(vec![
+ ((0x1d, 1), vec![0x0066, 0x0069]),
+ ((0x1e, 1), vec![0x00a0]),
+ ((0x1f, 1), vec![0x0066, 0x0066]),
+ ((0x20, 1), vec![0x0020]),
+ ])
+ );
+ }
+
+ #[test]
+ fn parse_cid_system_info() {
+ let data = b"/CIDSystemInfo <<
+/Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+";
+ assert!(cid_system_info(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cid_system_info_dict_dup() {
+ let data = b"/CIDSystemInfo 3 dict dup begin
+ /Registry (callas) def
+ /Ordering (MyriadPro-Regular14-UCMap) def
+ /Supplement 0 def
+end def
+";
+ assert!(cid_system_info(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cid_system_info_with_spaces() {
+ let data = b"/CIDSystemInfo
+<< /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n";
+ assert!(cid_system_info(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_name() {
+ let data = b"/CMapName /Adobe-Identity-UCS def\n";
+ assert!(cmap_name(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_name2() {
+ let data = b"/CMapName /Adobe-UCS-0 def\n";
+ assert!(cmap_name(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_type() {
+ let data = b"/CMapType 2 def\n";
+ assert!(cmap_type(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_version() {
+ let data = b"/CMapVersion 0 def\n";
+ assert!(cmap_version(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_version2() {
+ let data = b"/CMapVersion 10.001 def\n";
+ assert!(cmap_version(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_uidoffset() {
+ let data = b"/UIDOffset 950 def\n";
+ assert!(uidoffset(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_xuid() {
+ let data = b"/XUID [1 10 25343] def\n";
+ assert!(xuid(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_wmode() {
+ let data = b"/WMode 0 def\n";
+ assert!(wmode(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_section_1() {
+ let data = b"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo <<
+/Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName /Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+96 beginbfrange
+<0000> <00FF> <0000>
+<0100> <01FF> <0100>
+<0200> <02FF> <0200>
+<0300> <03FF> <0300>
+<0400> <04FF> <0400>
+<0500> <05FF> <0500>
+<0600> <06FF> <0600>
+<0700> <07FF> <0700>
+<0800> <08FF> <0800>
+<0900> <09FF> <0900>
+<0A00> <0AFF> <0A00>
+<0B00> <0BFF> <0B00>
+<0C00> <0CFF> <0C00>
+<0D00> <0DFF> <0D00>
+<0E00> <0EFF> <0E00>
+<0F00> <0FFF> <0F00>
+<1000> <10FF> <1000>
+<1100> <11FF> <1100>
+<1200> <12FF> <1200>
+<1300> <13FF> <1300>
+<1400> <14FF> <1400>
+<1500> <15FF> <1500>
+<1600> <16FF> <1600>
+<1700> <17FF> <1700>
+<1800> <18FF> <1800>
+<1900> <19FF> <1900>
+<1A00> <1AFF> <1A00>
+<1B00> <1BFF> <1B00>
+<1C00> <1CFF> <1C00>
+<1D00> <1DFF> <1D00>
+<1E00> <1EFF> <1E00>
+<1F00> <1FFF> <1F00>
+<2000> <20FF> <2000>
+<2100> <21FF> <2100>
+<2200> <22FF> <2200>
+<2300> <23FF> <2300>
+<2400> <24FF> <2400>
+<2500> <25FF> <2500>
+<2600> <26FF> <2600>
+<2700> <27FF> <2700>
+<2800> <28FF> <2800>
+<2900> <29FF> <2900>
+<2A00> <2AFF> <2A00>
+<2B00> <2BFF> <2B00>
+<2C00> <2CFF> <2C00>
+<2D00> <2DFF> <2D00>
+<2E00> <2EFF> <2E00>
+<2F00> <2FFF> <2F00>
+<3000> <30FF> <3000>
+<3100> <31FF> <3100>
+<3200> <32FF> <3200>
+<3300> <33FF> <3300>
+<3400> <34FF> <3400>
+<3500> <35FF> <3500>
+<3600> <36FF> <3600>
+<3700> <37FF> <3700>
+<3800> <38FF> <3800>
+<3900> <39FF> <3900>
+<3A00> <3AFF> <3A00>
+<3B00> <3BFF> <3B00>
+<3C00> <3CFF> <3C00>
+<3D00> <3DFF> <3D00>
+<3E00> <3EFF> <3E00>
+<3F00> <3FFF> <3F00>
+<4000> <40FF> <4000>
+<4100> <41FF> <4100>
+<4200> <42FF> <4200>
+<4300> <43FF> <4300>
+<4400> <44FF> <4400>
+<4500> <45FF> <4500>
+<4600> <46FF> <4600>
+<4700> <47FF> <4700>
+<4800> <48FF> <4800>
+<4900> <49FF> <4900>
+<4A00> <4AFF> <4A00>
+<4B00> <4BFF> <4B00>
+<4C00> <4CFF> <4C00>
+<4D00> <4DFF> <4D00>
+<4E00> <4EFF> <4E00>
+<4F00> <4FFF> <4F00>
+<5000> <50FF> <5000>
+<5100> <51FF> <5100>
+<5200> <52FF> <5200>
+<5300> <53FF> <5300>
+<5400> <54FF> <5400>
+<5500> <55FF> <5500>
+<5600> <56FF> <5600>
+<5700> <57FF> <5700>
+<5800> <58FF> <5800>
+<5900> <59FF> <5900>
+<5A00> <5AFF> <5A00>
+<5B00> <5BFF> <5B00>
+<5C00> <5CFF> <5C00>
+<5D00> <5DFF> <5D00>
+<5E00> <5EFF> <5E00>
+<5F00> <5FFF> <5F00>
+endbfrange
+96 beginbfrange
+<6000> <60FF> <6000>
+<6100> <61FF> <6100>
+<6200> <62FF> <6200>
+<6300> <63FF> <6300>
+<6400> <64FF> <6400>
+<6500> <65FF> <6500>
+<6600> <66FF> <6600>
+<6700> <67FF> <6700>
+<6800> <68FF> <6800>
+<6900> <69FF> <6900>
+<6A00> <6AFF> <6A00>
+<6B00> <6BFF> <6B00>
+<6C00> <6CFF> <6C00>
+<6D00> <6DFF> <6D00>
+<6E00> <6EFF> <6E00>
+<6F00> <6FFF> <6F00>
+<7000> <70FF> <7000>
+<7100> <71FF> <7100>
+<7200> <72FF> <7200>
+<7300> <73FF> <7300>
+<7400> <74FF> <7400>
+<7500> <75FF> <7500>
+<7600> <76FF> <7600>
+<7700> <77FF> <7700>
+<7800> <78FF> <7800>
+<7900> <79FF> <7900>
+<7A00> <7AFF> <7A00>
+<7B00> <7BFF> <7B00>
+<7C00> <7CFF> <7C00>
+<7D00> <7DFF> <7D00>
+<7E00> <7EFF> <7E00>
+<7F00> <7FFF> <7F00>
+<8000> <80FF> <8000>
+<8100> <81FF> <8100>
+<8200> <82FF> <8200>
+<8300> <83FF> <8300>
+<8400> <84FF> <8400>
+<8500> <85FF> <8500>
+<8600> <86FF> <8600>
+<8700> <87FF> <8700>
+<8800> <88FF> <8800>
+<8900> <89FF> <8900>
+<8A00> <8AFF> <8A00>
+<8B00> <8BFF> <8B00>
+<8C00> <8CFF> <8C00>
+<8D00> <8DFF> <8D00>
+<8E00> <8EFF> <8E00>
+<8F00> <8FFF> <8F00>
+<9000> <90FF> <9000>
+<9100> <91FF> <9100>
+<9200> <92FF> <9200>
+<9300> <93FF> <9300>
+<9400> <94FF> <9400>
+<9500> <95FF> <9500>
+<9600> <96FF> <9600>
+<9700> <97FF> <9700>
+<9800> <98FF> <9800>
+<9900> <99FF> <9900>
+<9A00> <9AFF> <9A00>
+<9B00> <9BFF> <9B00>
+<9C00> <9CFF> <9C00>
+<9D00> <9DFF> <9D00>
+<9E00> <9EFF> <9E00>
+<9F00> <9FFF> <9F00>
+<A000> <A0FF> <A000>
+<A100> <A1FF> <A100>
+<A200> <A2FF> <A200>
+<A300> <A3FF> <A300>
+<A400> <A4FF> <A400>
+<A500> <A5FF> <A500>
+<A600> <A6FF> <A600>
+<A700> <A7FF> <A700>
+<A800> <A8FF> <A800>
+<A900> <A9FF> <A900>
+<AA00> <AAFF> <AA00>
+<AB00> <ABFF> <AB00>
+<AC00> <ACFF> <AC00>
+<AD00> <ADFF> <AD00>
+<AE00> <AEFF> <AE00>
+<AF00> <AFFF> <AF00>
+<B000> <B0FF> <B000>
+<B100> <B1FF> <B100>
+<B200> <B2FF> <B200>
+<B300> <B3FF> <B300>
+<B400> <B4FF> <B400>
+<B500> <B5FF> <B500>
+<B600> <B6FF> <B600>
+<B700> <B7FF> <B700>
+<B800> <B8FF> <B800>
+<B900> <B9FF> <B900>
+<BA00> <BAFF> <BA00>
+<BB00> <BBFF> <BB00>
+<BC00> <BCFF> <BC00>
+<BD00> <BDFF> <BD00>
+<BE00> <BEFF> <BE00>
+<BF00> <BFFF> <BF00>
+endbfrange
+64 beginbfrange
+<C000> <C0FF> <C000>
+<C100> <C1FF> <C100>
+<C200> <C2FF> <C200>
+<C300> <C3FF> <C300>
+<C400> <C4FF> <C400>
+<C500> <C5FF> <C500>
+<C600> <C6FF> <C600>
+<C700> <C7FF> <C700>
+<C800> <C8FF> <C800>
+<C900> <C9FF> <C900>
+<CA00> <CAFF> <CA00>
+<CB00> <CBFF> <CB00>
+<CC00> <CCFF> <CC00>
+<CD00> <CDFF> <CD00>
+<CE00> <CEFF> <CE00>
+<CF00> <CFFF> <CF00>
+<D000> <D0FF> <D000>
+<D100> <D1FF> <D100>
+<D200> <D2FF> <D200>
+<D300> <D3FF> <D300>
+<D400> <D4FF> <D400>
+<D500> <D5FF> <D500>
+<D600> <D6FF> <D600>
+<D700> <D7FF> <D700>
+<D800> <D8FF> <D800>
+<D900> <D9FF> <D900>
+<DA00> <DAFF> <DA00>
+<DB00> <DBFF> <DB00>
+<DC00> <DCFF> <DC00>
+<DD00> <DDFF> <DD00>
+<DE00> <DEFF> <DE00>
+<DF00> <DFFF> <DF00>
+<E000> <E0FF> <E000>
+<E100> <E1FF> <E100>
+<E200> <E2FF> <E200>
+<E300> <E3FF> <E300>
+<E400> <E4FF> <E400>
+<E500> <E5FF> <E500>
+<E600> <E6FF> <E600>
+<E700> <E7FF> <E700>
+<E800> <E8FF> <E800>
+<E900> <E9FF> <E900>
+<EA00> <EAFF> <EA00>
+<EB00> <EBFF> <EB00>
+<EC00> <ECFF> <EC00>
+<ED00> <EDFF> <ED00>
+<EE00> <EEFF> <EE00>
+<EF00> <EFFF> <EF00>
+<F000> <F0FF> <F000>
+<F100> <F1FF> <F100>
+<F200> <F2FF> <F200>
+<F300> <F3FF> <F300>
+<F400> <F4FF> <F400>
+<F500> <F5FF> <F500>
+<F600> <F6FF> <F600>
+<F700> <F7FF> <F700>
+<F800> <F8FF> <F800>
+<F900> <F9FF> <F900>
+<FA00> <FAFF> <FA00>
+<FB00> <FBFF> <FB00>\r
+<FC00> <FCFF> <FC00>
+<FD00> <FDFF> <FD00>
+<FE00> <FEFF> <FE00>
+<FF00> <FFFF> <FF00>
+endbfrange
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_section_2() {
+ let data = b"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CMapType 2 def
+/CMapName/R27 def
+1 begincodespacerange
+<0000><ffff>
+endcodespacerange
+78 beginbfrange
+<0020><0020><0020>
+<0028><0028><0028>
+<0029><0029><0029>
+<002b><002b><002b>
+<002c><002c><002c>
+<002d><002d><002d>
+<002e><002e><002e>
+<002f><002f><002f>
+<0030><0030><0030>
+<0031><0031><0031>
+<0032><0032><0032>
+<0033><0033><0033>
+<0034><0034><0034>
+<0035><0035><0035>
+<0036><0036><0036>
+<0037><0037><0037>
+<0038><0038><0038>
+<0039><0039><0039>
+<003a><003a><003a>
+<003d><003d><003d>
+<0041><0041><0041>
+<0042><0042><0042>
+<0043><0043><0043>
+<0044><0044><0044>
+<0045><0045><0045>
+<0046><0046><0046>
+<0047><0047><0047>
+<0048><0048><0048>
+<0049><0049><0049>
+<004a><004a><004a>
+<004b><004b><004b>
+<004c><004c><004c>
+<004d><004d><004d>
+<004e><004e><004e>
+<004f><004f><004f>
+<0050><0050><0050>
+<0052><0052><0052>
+<0053><0053><0053>
+<0054><0054><0054>
+<0055><0055><0055>
+<0056><0056><0056>
+<0057><0057><0057>
+<0058><0058><0058>
+<005a><005a><005a>
+<005c><005c><005c>
+<0061><0061><0061>
+<0062><0062><0062>
+<0063><0063><0063>
+<0064><0064><0064>
+<0065><0065><0065>
+<0066><0066><0066>
+<0067><0067><0067>
+<0068><0068><0068>
+<0069><0069><0069>
+<006a><006a><006a>
+<006b><006b><006b>
+<006c><006c><006c>
+<006d><006d><006d>
+<006e><006e><006e>
+<006f><006f><006f>
+<0070><0070><0070>
+<0072><0072><0072>
+<0073><0073><0073>
+<0074><0074><0074>
+<0075><0075><0075>
+<0076><0076><0076>
+<0077><0077><0077>
+<0078><0078><0078>
+<0079><0079><0079>
+<007a><007a><007a>
+<007c><007c><007c>
+<00a3><00a3><00a3>
+<00d6><00d6><00d6>
+<00df><00df><00df>
+<00e4><00e4><00e4>
+<00f6><00f6><00f6>
+<00fc><00fc><00fc>
+<2019><2019><2019>
+endbfrange
+endcmap
+CMapName currentdict /CMap defineresource pop
+end end
+";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_section_bfchar() {
+ let data = b"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo
+<< /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def
+/CMapName /Adobe-UCS-0 def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+36 beginbfchar
+<0000> <0000>
+<0001> <004C>
+<0002> <0069>
+<0003> <0073>
+<0004> <0074>
+<0005> <0061>
+<0006> <006F>
+<0007> <0070>
+<0008> <0065>
+<0009> <0072>
+<000A> <0063>
+<000B> <006A>
+<000C> <007A>
+<000D> <006B>
+<000E> <0064>
+<000F> <0032>
+<0010> <0030>
+<0011> <0033>
+<0012> <002D>
+<0013> <0035>
+<0014> <0031>
+<0015> <0039>
+<0016> <0034>
+<0017> <0057>
+<0018> <006C>
+<0019> <0075>
+<001A> <0142>
+<001B> <0079>
+<001C> <0077>
+<001D> <004F>
+<001E> <0044>
+<001F> <0052>
+<0020> <0068>
+<0021> <006E>
+<0022> <004B>
+<0023> <0067>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_section_with_discontigous_range() {
+ let data = b"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo
+<< /Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName /Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+2 beginbfrange
+<0000> <005E> <0020>
+<005F> <0061> [<D83DDE00> <D83DDD27> <D83DDD28>]
+endbfrange
+1 beginbfchar
+<3A51> <D840DC3E>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_truetype_cmap_section_with_1byte_bfchars() {
+ let data = b"/CIDInit/ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo<<
+/Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName/Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<00> <FF>
+endcodespacerange
+29 beginbfchar
+<01> <0054>
+<02> <0068>
+<03> <0065>
+<04> <0020>
+<05> <0044>
+<06> <0061>
+<07> <006E>
+<08> <0067>
+<09> <0072>
+<0A> <006F>
+<0B> <0066>
+<0C> <0045>
+<0D> <0062>
+<0E> <006B>
+<0F> <0073>
+<10> <004A>
+<11> <0069>
+<12> <0075>
+<13> <0063>
+<14> <003A>
+<15> <0070>
+<16> <0074>
+<17> <002F>
+<18> <0076>
+<19> <0042>
+<1A> <0079>
+<1B> <002E>
+<1C> <006D>
+<1D> <006C>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end\n";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_section_with_lowercase_pracset_and_nospace_target_string() {
+ let data = b"/CIDInit /Procset findresource begin
+12 dict begin
+begincmap
+/CMapType 2 def
+1 begincodespacerange
+<0000><ffff>
+endcodespacerange
+4 beginbfchar
+<1D50><AC1C>
+<1E29><ACF5>
+<43ED><D2B9>
+<46FC><D5C8>
+endbfchar
+1 beginbfrange
+<067B><0692><0020>
+endbfrange
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end\n";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+ #[test]
+ fn parse_cmap_section_error() {
+ let data = b"%!PS-Adobe-3.0 Resource-CMap
+%%DocumentNeededResources: ProcSet (CIDInit)
+%%IncludeResource: ProcSet (CIDInit)
+%%BeginResource: CMap (MyriadPro-Regular14-UCMap)
+%%Title: (MyriadPro-Regular14-UCMap callas MyriadPro-Regular14-UCMap 0)
+%%EndComments
+
+/CIDInit /ProcSet findresource begin
+
+12 dict begin
+
+begincmap
+
+/CIDSystemInfo 3 dict dup begin
+ /Registry (callas) def
+ /Ordering (MyriadPro-Regular14-UCMap) def
+ /Supplement 0 def
+end def
+
+/CMapName /MyriadPro-Regular14-UCMap def
+/CMapType 2 def
+
+1 begincodespacerange
+<1e> <a9>
+endcodespacerange
+7 beginbfchar
+<1e> <00A0>
+<1f> <0066 0066>
+<20> <0020>
+<56> <0056>
+<5f> <005F>
+<96> <2013>
+<a9> <00A9>
+endbfchar
+8 beginbfrange
+<28> <29> <0028>
+<2c> <3a> <002C>
+<41> <4b> <0041>
+<4d> <54> <004D>
+<61> <69> <0061>
+<6c> <70> <006C>
+<72> <77> <0072>
+<79> <7a> <0079>
+endbfrange
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end
+
+%%EndResource
+%%EOF
+";
+ let res = cmap_stream(test_span(data));
+ println!("{:#?}", res);
+ assert!(res.is_ok())
+ }
+
+ #[test]
+ fn parse_cmap_byte_order_mark() {
+ let data = b"\xEF\xBB\xBF/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo << /Registry (Adobe)/Ordering (UCS)/Supplement 0>> def
+/CMapName /Adobe-Identity-UCS def /CMapType 2 def
+1 begincodespacerange
+<0003><0081>
+endcodespacerange
+23 beginbfrange
+<0025><0025><0042>
+<004F><004F><006C>
+<0052><0052><006F>
+<0046><0046><0063>
+<004E><004E><006B>
+<0048><0048><0065>
+<0047><0047><0064>
+<0003><0003><0020>
+<0049><0049><0066>
+<0055><0055><0072>
+<0051><0051><006E>
+<005A><005A><0077>
+<0044><0044><0061>
+<0053><0053><0070>
+<004C><004C><0069>
+<0057><0057><0074>
+<0012><0012><002F>
+<0029><0029><0046>
+<0081><0081><00FC>
+<0031><0031><004E>
+<0058><0058><0075>
+<004A><004A><0067>
+<0056><0056><0073>
+endbfrange
+endcmap CMapName currentdict /CMap defineresource pop end end";
+ assert!(cmap_stream(test_span(data)).is_ok())
+ }
+}
diff --git a/vendor/lopdf/src/parser/mod.rs b/vendor/lopdf/src/parser/mod.rs
new file mode 100644
index 000000000..f0944be52
--- /dev/null
+++ b/vendor/lopdf/src/parser/mod.rs
@@ -0,0 +1,1336 @@
+use super::{Dictionary, Object, ObjectId, Reader, Stream, StringFormat};
+use crate::Error;
+use crate::content::*;
+use crate::error;
+use crate::xref::*;
+use std::collections::HashSet;
+use std::str::{self, FromStr};
+
+use nom::branch::alt;
+use nom::bytes::complete::{tag, take, take_while, take_while_m_n, take_while1};
+use nom::character::complete::multispace1;
+use nom::character::complete::{digit0, digit1, one_of};
+use nom::character::complete::{space0, space1};
+use nom::combinator::cut;
+use nom::combinator::{map, map_opt, map_res, opt, verify};
+use nom::error::{ErrorKind, ParseError};
+use nom::multi::{fold_many0, fold_many1, many0, many0_count};
+use nom::sequence::{delimited, pair, preceded, separated_pair, terminated};
+use nom::{AsBytes, AsChar, IResult, Input, Parser};
+
+pub(crate) mod cmap_parser;
+
+pub(crate) type ParserInput<'a> = &'a [u8];
+// Change this to something else that implements ParseError to get a
+// different error type out of nom.
+pub(crate) type NomError<'a> = nom::error::Error<ParserInput<'a>>;
+
+pub(crate) type NomResult<'a, O, E = NomError<'a>> = IResult<ParserInput<'a>, O, E>;
+
+#[inline]
+fn strip_nom<O>(r: NomResult<O>) -> Option<O> {
+ r.ok().map(|(_, o)| o)
+}
+
+#[inline]
+fn convert_result<O, E>(result: Result<O, E>, input: ParserInput, error_kind: ErrorKind) -> NomResult<O> {
+ result.map(|o| (input, o)).map_err(|_| {
+ // this is a unit bind if NomError = ()
+ let err: NomError = nom::error::Error::from_error_kind(input, error_kind);
+ nom::Err::Error(err)
+ })
+}
+
+#[inline]
+fn offset_stream(object: &mut Object, offset: usize) {
+ if let Object::Stream(stream) = object {
+ stream.start_position = stream.start_position.and_then(|sp| sp.checked_add(offset));
+ }
+}
+
+pub(crate) fn eol(input: ParserInput) -> NomResult<ParserInput> {
+ alt((tag(&b"\r\n"[..]), tag(&b"\n"[..]), tag(&b"\r"[..]))).parse(input)
+}
+
+pub(crate) fn comment(input: ParserInput) -> NomResult<()> {
+ map((tag(&b"%"[..]), take_while(|c: u8| !b"\r\n".contains(&c)), eol), |_| ()).parse(input)
+}
+
+#[inline]
+fn is_whitespace(c: u8) -> bool {
+ b" \t\n\r\0\x0C".contains(&c)
+}
+
+#[inline]
+fn is_delimiter(c: u8) -> bool {
+ b"()<>[]{}/%".contains(&c)
+}
+
+#[inline]
+fn is_regular(c: u8) -> bool {
+ !is_whitespace(c) && !is_delimiter(c)
+}
+
+#[inline]
+fn is_direct_literal_string(c: u8) -> bool {
+ !b"()\\\r\n".contains(&c)
+}
+
+fn white_space(input: ParserInput) -> NomResult<()> {
+ map(take_while(is_whitespace), |_| ()).parse(input)
+}
+
+fn space(input: ParserInput) -> NomResult<()> {
+ fold_many0(
+ alt((map(take_while1(is_whitespace), |_| ()), comment)),
+ || {},
+ |_, _| (),
+ )
+ .parse(input)
+}
+
+fn integer(input: ParserInput) -> NomResult<i64> {
+ let (i, _) = pair(opt(one_of("+-")), digit1).parse(input)?;
+
+ let int_input = &input[..input.len() - i.len()];
+ convert_result(i64::from_str(str::from_utf8(int_input).unwrap()), i, ErrorKind::Digit)
+}
+
+fn real(input: ParserInput) -> NomResult<f32> {
+ let (i, _) = pair(
+ opt(one_of("+-")),
+ alt((
+ map((digit1, tag(&b"."[..]), digit0), |_| ()),
+ map(pair(tag(&b"."[..]), digit1), |_| ()),
+ )),
+ )
+ .parse(input)?;
+
+ let float_input = &input[..input.len() - i.len()];
+ convert_result(f32::from_str(str::from_utf8(float_input).unwrap()), i, ErrorKind::Digit)
+}
+
+pub(crate) fn hex_char(input: ParserInput) -> NomResult<u8> {
+ map_res(
+ verify(take(2usize), |h: ParserInput| {
+ h.as_bytes().iter().copied().all(AsChar::is_hex_digit)
+ }),
+ |x: ParserInput| u8::from_str_radix(str::from_utf8(x).unwrap(), 16),
+ )
+ .parse(input)
+}
+
+fn oct_char(input: ParserInput) -> NomResult<u8> {
+ map_res(
+ take_while_m_n(1, 3, AsChar::is_oct_digit),
+ // Spec requires us to ignore any overflow.
+ |x: ParserInput| u16::from_str_radix(str::from_utf8(x).unwrap(), 8).map(|o| o as u8),
+ )
+ .parse(input)
+}
+
+pub(crate) fn name(input: ParserInput) -> NomResult<Vec<u8>> {
+ preceded(
+ tag(&b"/"[..]),
+ many0(alt((
+ preceded(tag(&b"#"[..]), hex_char),
+ map_opt(take(1usize), |c: ParserInput| {
+ if c[0] != b'#' && is_regular(c[0]) {
+ Some(c[0])
+ } else {
+ None
+ }
+ }),
+ ))),
+ )
+ .parse(input)
+}
+
+fn escape_sequence(input: ParserInput) -> NomResult<Option<u8>> {
+ preceded(
+ tag(&b"\\"[..]),
+ alt((
+ map(oct_char, Some),
+ map(eol, |_| None),
+ map(tag(&b"n"[..]), |_| Some(b'\n')),
+ map(tag(&b"r"[..]), |_| Some(b'\r')),
+ map(tag(&b"t"[..]), |_| Some(b'\t')),
+ map(tag(&b"b"[..]), |_| Some(b'\x08')),
+ map(tag(&b"f"[..]), |_| Some(b'\x0C')),
+ map(take(1usize), |c: ParserInput| Some(c[0])),
+ )),
+ )
+ .parse(input)
+}
+
+enum InnerLiteralString<'a> {
+ Direct(ParserInput<'a>),
+ Escape(Option<u8>),
+ Eol(ParserInput<'a>),
+ Nested(Vec<u8>),
+}
+
+impl InnerLiteralString<'_> {
+ fn push(&self, output: &mut Vec<u8>) {
+ match self {
+ InnerLiteralString::Direct(s) | InnerLiteralString::Eol(s) => output.extend_from_slice(s),
+ InnerLiteralString::Escape(e) => output.extend(e),
+ InnerLiteralString::Nested(n) => output.extend_from_slice(n),
+ }
+ }
+}
+
+fn inner_literal_string(depth: usize) -> impl Fn(ParserInput) -> NomResult<Vec<u8>> {
+ move |input| {
+ fold_many0(
+ alt((
+ map(take_while1(is_direct_literal_string), InnerLiteralString::Direct),
+ map(escape_sequence, InnerLiteralString::Escape),
+ map(eol, InnerLiteralString::Eol),
+ map(nested_literal_string(depth), InnerLiteralString::Nested),
+ )),
+ Vec::new,
+ |mut out: Vec<u8>, value| {
+ value.push(&mut out);
+ out
+ },
+ )
+ .parse(input)
+ }
+}
+
+fn nested_literal_string(depth: usize) -> impl Fn(ParserInput) -> NomResult<Vec<u8>> {
+ move |input| {
+ if depth == 0 {
+ map(verify(tag(&b"too deep"[..]), |_: &[u8]| false), |_| vec![]).parse(input)
+ } else {
+ map(
+ delimited(tag(&b"("[..]), inner_literal_string(depth - 1), tag(&b")"[..])),
+ |mut content| {
+ content.insert(0, b'(');
+ content.push(b')');
+ content
+ },
+ )
+ .parse(input)
+ }
+ }
+}
+
+fn literal_string(input: ParserInput) -> NomResult<Vec<u8>> {
+ delimited(
+ tag(&b"("[..]),
+ inner_literal_string(crate::reader::MAX_BRACKET),
+ tag(&b")"[..]),
+ )
+ .parse(input)
+}
+
+#[inline]
+fn hex_digit(input: ParserInput) -> NomResult<u8> {
+ map_opt(take(1usize), |c: ParserInput| {
+ str::from_utf8(c).ok().and_then(|c| u8::from_str_radix(c, 16).ok())
+ })
+ .parse(input)
+}
+
+fn hexadecimal_string(input: ParserInput) -> NomResult<Object> {
+ map(
+ delimited(
+ tag(&b"<"[..]),
+ terminated(
+ fold_many0(
+ preceded(white_space, hex_digit),
+ || -> (Vec<u8>, bool) { (Vec::new(), false) },
+ |state, c| match state {
+ (mut out, false) => {
+ out.push(c << 4);
+ (out, true)
+ }
+ (mut out, true) => {
+ *out.last_mut().unwrap() |= c;
+ (out, false)
+ }
+ },
+ ),
+ white_space,
+ ),
+ tag(&b">"[..]),
+ ),
+ |(bytes, _)| Object::String(bytes, StringFormat::Hexadecimal),
+ )
+ .parse(input)
+}
+
+fn boolean(input: ParserInput) -> NomResult<Object> {
+ alt((
+ map(tag(&b"true"[..]), |_| Object::Boolean(true)),
+ map(tag(&b"false"[..]), |_| Object::Boolean(false)),
+ ))
+ .parse(input)
+}
+
+fn null(input: ParserInput) -> NomResult<Object> {
+ map(tag(&b"null"[..]), |_| Object::Null).parse(input)
+}
+
+fn array(depth: usize) -> impl Fn(ParserInput) -> NomResult<Vec<Object>> {
+ move |input| {
+ delimited(
+ pair(tag(&b"["[..]), space),
+ many0(_direct_object(depth)),
+ tag(&b"]"[..]),
+ )
+ .parse(input)
+ }
+}
+
+pub(crate) fn dictionary(input: ParserInput) -> NomResult<Dictionary> {
+ _dictionary(crate::reader::MAX_NESTING_DEPTH)(input)
+}
+
+fn _dictionary(depth: usize) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
+ move |input| delimited(pair(tag(&b"<<"[..]), space), inner_dictionary(depth), tag(&b">>"[..])).parse(input)
+}
+
+fn inner_dictionary(depth: usize) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
+ move |input| {
+ fold_many0(
+ pair(terminated(name, space), _direct_object(depth)),
+ Dictionary::new,
+ |mut dict, (key, value)| {
+ dict.set(key, value);
+ dict
+ },
+ )
+ .parse(input)
+ }
+}
+
+pub(crate) fn dict_dup(input: ParserInput) -> NomResult<Dictionary> {
+ delimited(
+ (
+ digit1,
+ space1,
+ tag(&b"dict"[..]),
+ space1,
+ tag(&b"dup"[..]),
+ space1,
+ tag(&b"begin"[..]),
+ multispace1,
+ ),
+ fold_many0(
+ terminated(
+ pair(
+ terminated(name, space),
+ _direct_object(crate::reader::MAX_NESTING_DEPTH),
+ ),
+ pair(tag(&b"def"[..]), multispace1),
+ ),
+ Dictionary::new,
+ |mut dict, (key, value)| {
+ dict.set(key, value);
+ dict
+ },
+ ),
+ tag(&b"end"[..]),
+ )
+ .parse(input)
+}
+
+/// Recover the sole EOL-framed `endstream` immediately followed by `endobj`.
+/// The caller must pass only bytes up to the current indirect-object boundary
+/// so the scan cannot cross into a neighboring object.
+fn recover_stream_length(input: ParserInput) -> Option<(ParserInput, ParserInput)> {
+ const ENDSTREAM: &[u8] = b"endstream";
+ let mut recovered = None;
+
+ for (position, candidate) in input.windows(ENDSTREAM.len()).enumerate() {
+ if candidate != ENDSTREAM {
+ continue;
+ }
+
+ let data_end = if input[..position].ends_with(b"\r\n") {
+ position - 2
+ } else if input[..position].ends_with(b"\n") || input[..position].ends_with(b"\r") {
+ position - 1
+ } else {
+ continue;
+ };
+ let after_endstream = &input[position + ENDSTREAM.len()..];
+ let Ok((after_endobj, _)) = preceded(space, tag(&b"endobj"[..])).parse(after_endstream) else {
+ continue;
+ };
+ if after_endobj.first().is_some_and(|&byte| !is_whitespace(byte)) {
+ continue;
+ }
+ if recovered.is_some() {
+ return None;
+ }
+ recovered = Some((after_endstream, &input[..data_end]));
+ }
+
+ recovered
+}
+
+fn stream<'a>(
+ input: ParserInput<'a>, reader: &Reader, already_seen: &mut HashSet<ObjectId>, recover_length: bool,
+ recovery_bound: Option<usize>,
+) -> NomResult<'a, Object> {
+ let (i, dict) = terminated(dictionary, (space, tag(&b"stream"[..]), space0, eol)).parse(input)?;
+
+ if let Ok(length) = dict.get(b"Length").and_then(|value| {
+ if let Ok(id) = value.as_reference() {
+ reader.get_object(id, already_seen).and_then(|value| value.as_i64())
+ } else {
+ value.as_i64()
+ }
+ }) {
+ if length < 0 {
+ // artificial error kind is created to allow descriptive nom errors
+ return Err(nom::Err::Failure(NomError::from_error_kind(i, ErrorKind::LengthValue)));
+ }
+ let Ok(length) = usize::try_from(length) else {
+ return Err(nom::Err::Failure(NomError::from_error_kind(i, ErrorKind::LengthValue)));
+ };
+ match terminated(take(length), pair(opt(eol), tag(&b"endstream"[..]))).parse(i) {
+ Ok((remaining, data)) => Ok((remaining, Object::Stream(Stream::new(dict, data.to_vec())))),
+ Err(_) if recover_length && !reader.strict => {
+ // The scan must not cross into a neighbouring indirect object,
+ // so it stops at the xref-derived bound; parsing itself stays
+ // unbounded. The bound arrived here as `input.len() - end`, and
+ // `i` starts `input.len() - i.len()` bytes later, so the scan
+ // covers exactly the first `i.len() - bound` bytes of `i`.
+ let scan_end = recovery_bound.map_or(i.len(), |bound| i.len().saturating_sub(bound));
+ let Some((remaining, data)) = recover_stream_length(&i[..scan_end]) else {
+ return Err(nom::Err::Failure(NomError::from_error_kind(i, ErrorKind::LengthValue)));
+ };
+ log::warn!(
+ "Stream Length is {length}, but the unambiguous object boundary gives {} bytes; using the recovered length.",
+ data.len()
+ );
+ Ok((remaining, Object::Stream(Stream::new(dict, data.to_vec()))))
+ }
+ Err(_) => Err(nom::Err::Failure(NomError::from_error_kind(i, ErrorKind::LengthValue))),
+ }
+ } else {
+ // Return position relative to the start of the stream dictionary.
+ Ok((i, Object::Stream(Stream::with_position(dict, input.len() - i.len()))))
+ }
+}
+
+fn unsigned_int<I: FromStr>(input: ParserInput) -> NomResult<I> {
+ map_res(digit1, |digits: ParserInput| {
+ I::from_str(str::from_utf8(digits).unwrap())
+ })
+ .parse(input)
+}
+
+fn object_id(input: ParserInput) -> NomResult<ObjectId> {
+ pair(terminated(unsigned_int, space), terminated(unsigned_int, space)).parse(input)
+}
+
+fn reference(input: ParserInput) -> NomResult<Object> {
+ map(terminated(object_id, tag(&b"R"[..])), Object::Reference).parse(input)
+}
+
+fn _direct_objects(depth: usize) -> impl Fn(ParserInput) -> NomResult<Object> {
+ move |input| {
+ alt((
+ null,
+ boolean,
+ reference,
+ map(real, Object::Real),
+ map(integer, Object::Integer),
+ map(name, Object::Name),
+ map(literal_string, Object::string_literal),
+ hexadecimal_string,
+ map(array(depth), Object::Array),
+ map(_dictionary(depth), Object::Dictionary),
+ ))
+ .parse(input)
+ }
+}
+
+fn _direct_object(depth: usize) -> impl Fn(ParserInput) -> NomResult<Object> {
+ move |input| {
+ if depth == 0 {
+ return Err(nom::Err::Failure(NomError::from_error_kind(input, ErrorKind::TooLarge)));
+ }
+ terminated(_direct_objects(depth - 1), space).parse(input)
+ }
+}
+
+pub fn direct_object(input: ParserInput) -> Option<Object> {
+ strip_nom(_direct_object(crate::reader::MAX_NESTING_DEPTH)(input))
+}
+
+fn object<'a>(
+ input: ParserInput<'a>, reader: &Reader, already_seen: &mut HashSet<ObjectId>, recover_stream_length: bool,
+ recovery_bound: Option<usize>,
+) -> NomResult<'a, Object> {
+ terminated(
+ alt((
+ |input| stream(input, reader, already_seen, recover_stream_length, recovery_bound),
+ _direct_objects(crate::reader::MAX_NESTING_DEPTH),
+ )),
+ space,
+ )
+ .parse(input)
+}
+
+pub fn indirect_object(
+ input: ParserInput, offset: usize, expected_id: Option<ObjectId>, reader: &Reader,
+ already_seen: &mut HashSet<ObjectId>, recovery_bound: Option<usize>,
+) -> crate::Result<(ObjectId, Object)> {
+ // Every downstream slice is a suffix of `input`, so express the absolute
+ // end offset as the maximum length a suffix may have.
+ let recovery_bound = recovery_bound.map(|end| input.len().saturating_sub(end));
+ let (id, mut object) = _indirect_object(
+ input.take_from(offset),
+ offset,
+ expected_id,
+ reader,
+ already_seen,
+ true,
+ recovery_bound,
+ )?;
+
+ offset_stream(&mut object, offset);
+
+ Ok((id, object))
+}
+
+fn _indirect_object<'a>(
+ input: ParserInput<'a>, offset: usize, expected_id: Option<ObjectId>, reader: &Reader,
+ already_seen: &mut HashSet<ObjectId>, recover_stream_length: bool, recovery_bound: Option<usize>,
+) -> crate::Result<(ObjectId, Object)> {
+ let (i, (_, object_id)) = terminated((space, object_id), pair(tag(&b"obj"[..]), space))
+ .parse(input)
+ .map_err(|_| Error::IndirectObject { offset })?;
+ if let Some(expected_id) = expected_id
+ && object_id != expected_id
+ {
+ return Err(crate::error::Error::ObjectIdMismatch);
+ }
+
+ let object_offset = input.len() - i.len();
+ let (_, mut object) = terminated(
+ |i: ParserInput<'a>| object(i, reader, already_seen, recover_stream_length, recovery_bound),
+ (space, opt(tag(&b"endobj"[..])), space),
+ )
+ .parse(i)
+ .map_err(|_| Error::IndirectObject { offset })?;
+
+ offset_stream(&mut object, object_offset);
+
+ Ok((object_id, object))
+}
+
+pub fn header(input: ParserInput, strict: bool) -> Option<String> {
+ // Parse version digits (e.g. "1.7") separately from any trailing bytes
+ // before the newline. Some PDF generators (e.g. ImageMill) place binary
+ // marker bytes on the header line which would fail UTF-8 validation.
+ // In strict mode we reject such trailing bytes; in lenient mode we skip them.
+ let (_, (version_raw, trailing)) = delimited(
+ tag(&b"%PDF-"[..]),
+ pair(
+ take_while(|c: u8| c.is_ascii_digit() || c == b'.'),
+ take_while(|c: u8| !b"\r\n".contains(&c)),
+ ),
+ pair(eol, many0_count(comment)),
+ )
+ .parse(input)
+ .ok()?;
+
+ if strict && !trailing.is_empty() {
+ return None;
+ }
+
+ let version = str::from_utf8(version_raw).ok()?.to_string();
+ Some(version)
+}
+
+pub fn binary_mark(input: ParserInput) -> Option<Vec<u8>> {
+ strip_nom(
+ map_res(
+ delimited(
+ tag(&b"%"[..]),
+ take_while(|c: u8| !b"\r\n".contains(&c)),
+ pair(eol, many0_count(comment)),
+ ),
+ |v: ParserInput| Ok::<Vec<u8>, ()>(v.to_vec()),
+ )
+ .parse(input),
+ )
+}
+
+/// Decode CrossReferenceTable
+fn xref(input: ParserInput, strict: bool) -> NomResult<Xref> {
+ // ISO 32000-1 s7.5.4 requires every entry to be exactly 20 bytes, ending in one of the
+ // 2-byte terminators SP CR, SP LF or CR LF. Many generators instead emit 19-byte entries
+ // ending in a bare LF, which qpdf, pikepdf, PDFium and PDF.js all accept. Accept those
+ // too when parsing leniently, but keep the conforming 2-byte forms first in the `alt` so
+ // that a bare CR never matches the CR of a conforming CR LF and strands its LF.
+ let xref_eol = move |i| {
+ let conforming = alt((tag(&b" \r"[..]), tag(&b" \n"[..]), tag(&b"\r\n"[..])));
+ if strict {
+ map(conforming, |_| ()).parse(i)
+ } else {
+ map(alt((conforming, tag(&b"\n"[..]), tag(&b"\r"[..]))), |_| ()).parse(i)
+ }
+ };
+ let xref_entry = pair(
+ separated_pair(unsigned_int, tag(&b" "[..]), unsigned_int::<u32>),
+ delimited(tag(&b" "[..]), map(one_of("nf"), |k| k == 'n'), xref_eol),
+ );
+
+ let xref_section = pair(
+ separated_pair(unsigned_int::<usize>, tag(&b" "[..]), unsigned_int::<u32>),
+ preceded(pair(opt(tag(&b" "[..])), eol), many0(xref_entry)),
+ );
+
+ delimited(
+ pair(tag(&b"xref"[..]), preceded(opt(tag(&b" "[..])), eol)),
+ fold_many1(
+ xref_section,
+ || -> Xref { Xref::new(0, XrefType::CrossReferenceTable) },
+ |mut xref, ((start, _count), entries)| {
+ let mut skipped = 0usize;
+ for (index, ((offset, generation), is_normal)) in entries.into_iter().enumerate() {
+ if is_normal && let Ok(generation) = generation.try_into() {
+ // `start` is read from the subsection header, so it is untrusted:
+ // `start + index` can overflow, and object numbers are u32, so a
+ // `start` above u32::MAX would truncate into a valid-looking number
+ // that silently displaces a legitimate entry. Skip whatever cannot
+ // be represented, as an out-of-range generation is skipped above.
+ match start.checked_add(index).and_then(|id| u32::try_from(id).ok()) {
+ Some(id) => xref.insert(id, XrefEntry::Normal { offset, generation }),
+ None => skipped += 1,
+ }
+ }
+ }
+ if skipped > 0 {
+ log::warn!(
+ "cross-reference subsection starting at {start} has {skipped} entr{} with an object number beyond u32; skipping",
+ if skipped == 1 { "y" } else { "ies" }
+ );
+ }
+ xref
+ },
+ ),
+ space,
+ )
+ .parse(input)
+}
+
+fn trailer(input: ParserInput) -> NomResult<Dictionary> {
+ delimited(pair(tag(&b"trailer"[..]), space), dictionary, space).parse(input)
+}
+
+pub fn xref_and_trailer(input: ParserInput, reader: &Reader) -> crate::Result<(Xref, Dictionary)> {
+ let xref_trailer = map(pair(|i| xref(i, reader.strict), trailer), |(mut xref, trailer)| {
+ xref.size = trailer
+ .get(b"Size")
+ .and_then(Object::as_i64)
+ .map_err(|_| error::ParseError::InvalidTrailer)? as u32;
+ Ok((xref, trailer))
+ });
+ alt((
+ xref_trailer,
+ (|input| {
+ _indirect_object(input, 0, None, reader, &mut HashSet::new(), false, None)
+ .map(|(_, obj)| {
+ let res = match obj {
+ Object::Stream(stream) => decode_xref_stream_with_limit(stream, reader.max_decompressed_size),
+ _ => Err(crate::error::ParseError::InvalidXref.into()),
+ };
+ (input, res)
+ })
+ .map_err(|_| {
+ // artificial error kind is created to allow descriptive nom errors
+ nom::Err::Error(NomError::from_error_kind(input, ErrorKind::Fail))
+ })
+ }),
+ ))
+ .parse(input)
+ .map(|(_, o)| o)
+ .map_err(|_| error::ParseError::InvalidTrailer)?
+}
+
+pub fn xref_start(input: ParserInput) -> Option<i64> {
+ strip_nom(
+ delimited(
+ pair(tag(&b"startxref"[..]), preceded(opt(tag(&b" "[..])), eol)),
+ trim_spaces(integer),
+ (eol, tag(&b"%%EOF"[..]), space),
+ )
+ .parse(input),
+ )
+}
+
+fn trim_spaces<'a, O>(
+ p: impl Parser<ParserInput<'a>, Output = O, Error = NomError<'a>>,
+) -> impl Parser<ParserInput<'a>, Output = O, Error = NomError<'a>> {
+ delimited(many0(tag(" ")), p, many0(tag(" ")))
+}
+
+// The following code create parser to parse content stream.
+
+fn content_space(input: ParserInput) -> NomResult<()> {
+ map(take_while(|c| b" \t\r\n".contains(&c)), |_| ()).parse(input)
+}
+
+fn operator(input: ParserInput) -> NomResult<String> {
+ map_res(
+ take_while1(|c: u8| c.is_ascii_alphabetic() || b"*'\"".contains(&c)),
+ |op: ParserInput| str::from_utf8(op).map(Into::into),
+ )
+ .parse(input)
+}
+
+fn operand(input: ParserInput) -> NomResult<Object> {
+ terminated(
+ alt((
+ null,
+ boolean,
+ map(real, Object::Real),
+ map(integer, Object::Integer),
+ map(name, Object::Name),
+ map(literal_string, Object::string_literal),
+ hexadecimal_string,
+ map(array(crate::reader::MAX_NESTING_DEPTH), Object::Array),
+ map(dictionary, Object::Dictionary),
+ )),
+ content_space,
+ )
+ .parse(input)
+}
+
+fn operation(input: ParserInput) -> NomResult<Operation> {
+ map(
+ preceded(
+ // A comment consumes its end-of-line marker, so also skip any
+ // white space that follows it (e.g. an indented next line).
+ many0(terminated(comment, content_space)),
+ alt((inline_image, terminated(pair(many0(operand), operator), content_space))),
+ ),
+ |(operands, operator)| Operation { operator, operands },
+ )
+ .parse(input)
+}
+
+fn inline_image(input: ParserInput) -> NomResult<(Vec<Object>, String)> {
+ preceded(pair(tag(&b"BI"[..]), content_space), cut(inline_image_impl)).parse(input)
+}
+
+fn inline_image_impl(input: ParserInput) -> NomResult<(Vec<Object>, String)> {
+ let (input, stream_dict) = inner_dictionary(crate::reader::MAX_NESTING_DEPTH).parse(input)?;
+ let (input, _) = pair(tag(&b"ID"[..]), content_space).parse(input)?;
+ match image_data_stream(input, stream_dict) {
+ Ok((input, stream)) => {
+ let (input, _) = (content_space, tag(&b"EI"[..]), content_space).parse(input)?;
+ Ok((input, (vec![Object::Stream(stream)], String::from("BI"))))
+ }
+ Err(e) => {
+ // Skip to EI marker so the rest of the content stream can still be parsed.
+ log::warn!("Skipping unparseable inline image: {e}");
+ let bytes = input;
+ // EI must appear after whitespace to distinguish from data bytes.
+ let ei_pos = bytes
+ .windows(4)
+ .position(|w| {
+ (w[0] == b' ' || w[0] == b'\n' || w[0] == b'\r')
+ && w[1] == b'E'
+ && w[2] == b'I'
+ && (w[3] == b' ' || w[3] == b'\n' || w[3] == b'\r')
+ })
+ .ok_or_else(|| {
+ let err: NomError = nom::error::Error::from_error_kind(input, ErrorKind::Fail);
+ nom::Err::Failure(err)
+ })?;
+ let (input, _) = take(ei_pos + 3).parse(input).map_err(|_: nom::Err<()>| {
+ let err: NomError = nom::error::Error::from_error_kind(input, ErrorKind::Fail);
+ nom::Err::Failure(err)
+ })?;
+ let (input, _) = content_space(input)?;
+ Ok((input, (vec![], String::from("BI"))))
+ }
+ }
+}
+
+fn image_data_stream(input: ParserInput, stream_dict: Dictionary) -> crate::Result<(ParserInput, Stream)> {
+ let get_abbr = |key_abbr: &[u8], key: &[u8]| stream_dict.get(key_abbr).or_else(|_| stream_dict.get(key));
+ let width = get_abbr(b"W", b"Width")?.as_i64()? as usize;
+ let height = get_abbr(b"H", b"Height")?.as_i64()? as usize;
+ let bpc = get_abbr(b"BPC", b"BitsPerComponent")?.as_i64()? as usize;
+ let im = get_abbr(b"IM", b"ImageMask").and_then(|x| x.as_bool());
+ let num_colors = match im {
+ // If we have an image mask then we don't have a colorspace
+ Ok(true) => 1,
+ _ => {
+ let colorspace = get_abbr(b"CS", b"ColorSpace")?.as_name()?;
+ match colorspace {
+ b"DeviceGray" | b"Gray" => 1,
+ b"DeviceRGB" | b"RGB" => 3,
+ b"DeviceRGBA" | b"RGBA" => 4,
+ b"DeviceCMYK" | b"CMYK" => 4,
+ b"Pattern" => {
+ log::warn!("Pattern colorspace is not allowed in inline images");
+ return Err(Error::InvalidInlineImage(String::from(
+ "Pattern colorspace is not allowed in inline images",
+ )));
+ }
+ _ => {
+ log::warn!("Colorspace of inline image not recognized / not yet implemented");
+ return Err(Error::Unimplemented("inline image colorspaces"));
+ }
+ }
+ }
+ };
+
+ let stride = (width * (num_colors * bpc)).div_ceil(8);
+ let length = height * stride;
+
+ let (input, content) = match get_abbr(b"F", b"Filter") {
+ Err(_) => {
+ // no decompression needed as no filter was applied
+ take(length)
+ .parse(input)
+ .map_err(|_: nom::Err<()>| crate::error::ParseError::EndOfInput)?
+ }
+ Ok(Object::Name(_filter)) => {
+ log::warn!("Filters for inline images are not yet implemented");
+ return Err(Error::Unimplemented("filters for inline images"));
+ }
+ Ok(Object::Array(_filters)) => {
+ log::warn!("Filters for inline images are not yet implemented");
+ return Err(Error::Unimplemented("filters for inline images"));
+ }
+ Ok(obj) => {
+ log::warn!("Filter must be either a Name or and Array.");
+ return Err(Error::ObjectType {
+ expected: "Name or Array",
+ found: obj.enum_variant(),
+ });
+ }
+ };
+ Ok((input, Stream::new(stream_dict, content.to_vec())))
+}
+
+fn _content(input: ParserInput) -> NomResult<Content<Vec<Operation>>> {
+ delimited(
+ content_space,
+ map(many0(operation), |operations| Content { operations }),
+ many0(terminated(comment, content_space)),
+ )
+ .parse(input)
+}
+
+pub fn content(input: ParserInput) -> Option<Content<Vec<Operation>>> {
+ strip_nom(_content.parse(input))
+}
+
+pub fn content_strict(input: ParserInput) -> Result<Content<Vec<Operation>>, error::ParseError> {
+ let (rest, content) = _content
+ .parse(input)
+ .map_err(|_| error::ParseError::InvalidContentStream)?;
+ if !rest.is_empty() {
+ return Err(error::ParseError::InvalidContentStream);
+ }
+ Ok(content)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_span(s: &'_ [u8]) -> ParserInput<'_> {
+ s
+ }
+
+ fn tstrip<O>(r: NomResult<O>) -> Option<O> {
+ r.ok().and_then(|(i, o)| if !i.is_empty() { None } else { Some(o) })
+ }
+
+ #[test]
+ fn parse_real_number() {
+ let real = |i| tstrip(real(i));
+
+ assert_eq!(real(test_span(b"0.12")), Some(0.12));
+ assert_eq!(real(test_span(b"-.12")), Some(-0.12));
+ assert_eq!(real(test_span(b"10.")), Some(10.0));
+ }
+
+ #[test]
+ fn parse_string() {
+ let literal_string = |i| tstrip(literal_string(i));
+
+ let data = vec![
+ ("()", ""),
+ ("(text())", "text()"),
+ ("(text\r\n\\\\(nested\\t\\b\\f))", "text\r\n\\(nested\t\x08\x0C)"),
+ ("(text\\0\\53\\053\\0053)", "text\0++\x053"),
+ ("(text line\\\n())", "text line()"),
+ ];
+
+ for (input, expected) in data {
+ assert_eq!(
+ literal_string(test_span(input.as_bytes())),
+ Some(expected.as_bytes().to_vec()),
+ "input: {:?} output: {:?}",
+ input,
+ expected,
+ );
+ }
+ }
+
+ #[test]
+ fn parse_name() {
+ let (text, expected) = (b"/ABC#5f", b"ABC\x5F");
+ let result = tstrip(name(test_span(text)));
+ assert_eq!(result, Some(expected.to_vec()));
+
+ let (text, expected) = (b"/#cb#ce#cc#e5", b"\xcb\xce\xcc\xe5");
+ let result = tstrip(name(test_span(text)));
+ assert_eq!(result, Some(expected.to_vec()));
+ }
+
+ #[test]
+ /// Run `cargo test -- --nocapture` to see output
+ fn parse_content() {
+ let stream = b"
+2 J
+BT
+/F1 12 Tf
+0 Tc
+0 Tw
+72.5 712 TD
+[(Unencoded streams can be read easily) 65 (,) ] TJ
+0 -14 TD
+[(b) 20 (ut generally tak) 10 (e more space than \\311)] TJ
+T* (encoded streams.) Tj
+ ";
+ let content = tstrip(_content(test_span(stream)));
+ println!("{:?}", content);
+ assert!(content.is_some());
+ }
+
+ #[test]
+ fn hex_partial() {
+ // Example from PDF specification.
+ let out = tstrip(hexadecimal_string(test_span(b"<901FA>")));
+
+ match out {
+ Some(Object::String(s, _)) => assert_eq!(s, b"\x90\x1F\xA0".to_vec()),
+ _ => panic!("unexpected {:?}", out),
+ }
+ }
+
+ #[test]
+ fn hex_separated() {
+ let out = tstrip(hexadecimal_string(test_span(b"<9 01F A>")));
+
+ match out {
+ Some(Object::String(s, _)) => assert_eq!(s, b"\x90\x1F\xA0".to_vec()),
+ _ => panic!("unexpected {:?}", out),
+ }
+ }
+
+ #[test]
+ fn big_generation_value() {
+ let input = b"xref
+0 1
+0000000000 65536 f\x20
+0 16
+0000000000 65535 f\x20
+0000153238 00000 n\x20
+0000000019 00000 n\x20
+0000000313 00000 n\x20
+0000000333 00000 n\x20
+0000145531 00000 n\x20
+0000153407 00000 n\x20
+0000145554 00000 n\x20
+0000152303 00000 n\x20
+0000152324 00000 n\x20
+0000152514 00000 n\x20
+0000152880 00000 n\x20
+0000153106 00000 n\x20
+0000153139 00000 n\x20
+0000153532 00000 n\x20
+0000153629 00000 n\x20
+trailer
+<</Size 16/Root 14 0 R
+/Info 15 0 R
+/ID [ <9DDC4B621B3F485FF5ED0F57D00A028F>
+<9DDC4B621B3F485FF5ED0F57D00A028F> ]
+/DocChecksum /2BCC3C7DE26E6BF3573E4A6E8362221F
+>>
+startxref
+153804\x20
+%%EOF
+";
+ match xref(test_span(input), false) {
+ Ok((_, re)) => assert_eq!(re.entries.len(), 15),
+ Err(err) => panic!("unexpected {:?}", err),
+ }
+ }
+
+ #[test]
+ fn space_in_startxref_number() {
+ let input = b"startxref
+153804\x20
+%%EOF
+";
+ match xref_start(test_span(input)) {
+ Some(num) => assert_eq!(num, 153804),
+ None => panic!("could not parse number in startxref"),
+ }
+ }
+
+ #[test]
+ fn header_standard() {
+ // Standard header with proper EOL
+ let input = b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n";
+ assert_eq!(header(test_span(input), false), Some("1.7".to_string()));
+ }
+
+ #[test]
+ fn header_with_binary_bytes_on_same_line() {
+ // Some generators (e.g. ImageMill) place binary marker bytes on the
+ // header line without a separating newline or '%' prefix.
+ let input = b"%PDF-1.3 \xb0\x9f\x92\x9c\x9f\xd4\xe0\xce\xd0\xd0\xd0\r1 0 obj\r";
+ assert_eq!(header(test_span(input), false), Some("1.3".to_string()));
+ }
+
+ #[test]
+ fn header_with_binary_bytes_strict_rejects() {
+ // In strict mode, binary bytes on the header line should cause a
+ // parse failure (the raw bytes are not valid UTF-8).
+ let input = b"%PDF-1.3 \xb0\x9f\x92\x9c\x9f\xd4\xe0\xce\xd0\xd0\xd0\r1 0 obj\r";
+ assert_eq!(header(test_span(input), true), None);
+ }
+
+ #[test]
+ fn header_cr_line_ending() {
+ // CR-only line ending (common in older PDFs)
+ let input = b"%PDF-1.3\r%\xe2\xe3\xcf\xd3\r";
+ assert_eq!(header(test_span(input), false), Some("1.3".to_string()));
+ }
+
+ #[test]
+ fn header_crlf_line_ending() {
+ // CRLF line ending (common on Windows-generated PDFs)
+ let input = b"%PDF-1.7\r\n%\xe2\xe3\xcf\xd3\r\n";
+ assert_eq!(header(test_span(input), false), Some("1.7".to_string()));
+ }
+
+ #[test]
+ fn header_pdf_2_0() {
+ let input = b"%PDF-2.0\n%\xe2\xe3\xcf\xd3\n";
+ assert_eq!(header(test_span(input), false), Some("2.0".to_string()));
+ }
+
+ #[test]
+ fn content_with_comments() {
+ // It should be processed as usual but ignoring the comments
+ let input = b"0.5 0.5 0.5 setrgbcolor
+% This is a comment
+100 100 moveto
+(Hello, world!) show
+% Another comment
+";
+ let out = content(test_span(input)).unwrap();
+ let out_strict = content_strict(test_span(input)).unwrap();
+ assert_eq!(out.operations.len(), out_strict.operations.len());
+ assert_eq!(out.operations.len(), 3);
+ }
+
+ #[test]
+ fn content_with_comment_followed_by_indented_line() {
+ // A comment is equivalent to a single white-space character
+ // (ISO 32000-2, 7.2.4), so a line starting with white space right
+ // after a comment must not stop the parser (issue #535).
+ let input = b"BT /F1 24 Tf
+% comment
+ 100 100 Td (Hello World) Tj ET";
+ let out = content(test_span(input)).unwrap();
+ let out_strict = content_strict(test_span(input)).unwrap();
+ assert_eq!(out.operations.len(), out_strict.operations.len());
+ let ops: Vec<&str> = out.operations.iter().map(|o| o.operator.as_str()).collect();
+ assert_eq!(ops, vec!["BT", "Tf", "Td", "Tj", "ET"]);
+ }
+
+ #[test]
+ fn inline_image_unknown_colorspace_skipped() {
+ // Inline image with an unrecognized colorspace ("ICCBased" is not handled).
+ // The parser should skip it and still parse the surrounding operations.
+ let input = b"q 100 100 moveto
+BI /W 2 /H 2 /CS /ICCBased /BPC 8
+ID
+\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
+EI
+(Hello) Tj Q";
+ let out = content(test_span(input)).unwrap();
+ // Should have: q, moveto, BI (skipped), Tj, Q = 5 operations
+ let ops: Vec<&str> = out.operations.iter().map(|o| o.operator.as_str()).collect();
+ assert!(ops.contains(&"q"), "missing q, got: {:?}", ops);
+ assert!(ops.contains(&"Tj"), "missing Tj, got: {:?}", ops);
+ assert!(ops.contains(&"Q"), "missing Q, got: {:?}", ops);
+ }
+
+ #[test]
+ fn inline_image() {
+ let _ = env_logger::try_init();
+ let input = b"BI /W 4 /H 4 /CS /RGB /BPC 8
+ID
+00000z0z00zzz00z0zzz0zzzEI aazazaazzzaazazzzazzz
+EI";
+ let out = super::inline_image(test_span(input)).unwrap().1;
+ assert_eq!(&out.1, "BI");
+ assert_eq!(
+ &out.0[0].as_stream().unwrap().content,
+ b"00000z0z00zzz00z0zzz0zzzEI aazazaazzzaazazzzazzz"
+ )
+ }
+
+ #[test]
+ fn xref_trailing_space_after_keyword() {
+ // Some PDF generators emit "xref \n" with a trailing space.
+ let input = b"xref \n0 3\n0000000000 65535 f \n0000000017 00000 n \n0000000081 00000 n \ntrailer\n<</Size 3/Root 1 0 R>>\nstartxref\n175\n%%EOF\n";
+ match xref(test_span(input), false) {
+ Ok((_, re)) => assert_eq!(re.entries.len(), 2),
+ Err(err) => panic!("xref with trailing space should parse: {:?}", err),
+ }
+ }
+
+ #[test]
+ fn xref_entries_with_bare_eol_terminator() {
+ // ISO 32000-1 s7.5.4 requires 20-byte entries, so the terminator is two bytes
+ // (" \r", " \n" or "\r\n"). Many generators drop the padding space and emit
+ // 19-byte entries ending in a bare "\n"; qpdf, pikepdf, PDFium and PDF.js all
+ // accept these, so lenient parsing accepts them too.
+ for (name, input) in [
+ (
+ "bare LF",
+ &b"xref\n0 3\n0000000000 65535 f\n0000000017 00000 n\n0000000081 00000 n\ntrailer\n<</Size 3/Root 1 0 R>>\n"[..],
+ ),
+ (
+ "bare CR",
+ &b"xref\n0 3\n0000000000 65535 f\r0000000017 00000 n\r0000000081 00000 n\rtrailer\n<</Size 3/Root 1 0 R>>\n"[..],
+ ),
+ ] {
+ match xref(test_span(input), false) {
+ Ok((_, re)) => assert_eq!(re.entries.len(), 2, "{name} should yield both normal entries"),
+ Err(err) => panic!("19-byte entries ({name}) should parse when lenient: {err:?}"),
+ }
+ }
+ }
+
+ #[test]
+ fn xref_entries_with_bare_eol_rejected_when_strict() {
+ // The 19-byte form is non-conforming, so strict mode must keep rejecting it.
+ // At this level the rejection is indirect: the entries simply are not recognised,
+ // leaving an empty section whose unconsumed lines then displace `trailer`. Assert
+ // both halves -- the empty table here, and the document-level failure below.
+ let input =
+ b"xref\n0 3\n0000000000 65535 f\n0000000017 00000 n\n0000000081 00000 n\ntrailer\n<</Size 3/Root 1 0 R>>\n";
+ if let Ok((_, re)) = xref(test_span(input), true) {
+ assert_eq!(re.entries.len(), 0, "strict must not accept 19-byte entries");
+ }
+
+ // The contract that matters to callers: a document with 19-byte entries loads
+ // leniently and is refused under `LoadOptions::strict`. The 20-byte build of the
+ // very same document is the control -- it must load in *both* modes, so that the
+ // strict rejection below is attributable to the terminator and nothing else.
+ let load = |bytes: &[u8], strict: bool| {
+ crate::Document::load_mem_with_options(
+ bytes,
+ crate::LoadOptions {
+ strict,
+ ..Default::default()
+ },
+ )
+ };
+
+ for (name, term, strict_should_load) in [("19-byte", "\n", false), ("20-byte", " \n", true)] {
+ let header = "%PDF-1.7\n";
+ let obj1 = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
+ let obj2 = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
+ let obj3 = "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>\nendobj\n";
+ let o1 = header.len();
+ let o2 = o1 + obj1.len();
+ let o3 = o2 + obj2.len();
+ let body = format!("{header}{obj1}{obj2}{obj3}");
+ let xref_pos = body.len();
+ let doc = format!(
+ "{body}xref\n0 4\n0000000000 65535 f{term}{o1:010} 00000 n{term}{o2:010} 00000 n{term}\
+ {o3:010} 00000 n{term}trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n"
+ );
+
+ assert!(
+ load(doc.as_bytes(), false).is_ok(),
+ "{name} entries should load when lenient"
+ );
+ assert_eq!(
+ load(doc.as_bytes(), true).is_ok(),
+ strict_should_load,
+ "{name} entries under strict parsing"
+ );
+ }
+ }
+
+ #[test]
+ fn xref_entries_with_conforming_terminators() {
+ // The three 20-byte terminators of s7.5.4 must keep parsing in both modes. In
+ // particular the bare-CR alternative must not match the CR of a "\r\n" pair and
+ // strand its LF, which would break the following entry.
+ for (name, input) in [
+ (
+ "SP LF",
+ &b"xref\n0 3\n0000000000 65535 f \n0000000017 00000 n \n0000000081 00000 n \ntrailer\n<</Size 3/Root 1 0 R>>\n"[..],
+ ),
+ (
+ "SP CR",
+ &b"xref\n0 3\n0000000000 65535 f \r0000000017 00000 n \r0000000081 00000 n \rtrailer\n<</Size 3/Root 1 0 R>>\n"[..],
+ ),
+ (
+ "CR LF",
+ &b"xref\n0 3\n0000000000 65535 f\r\n0000000017 00000 n\r\n0000000081 00000 n\r\ntrailer\n<</Size 3/Root 1 0 R>>\n"[..],
+ ),
+ ] {
+ for strict in [false, true] {
+ match xref(test_span(input), strict) {
+ Ok((_, re)) => assert_eq!(re.entries.len(), 2, "{name} (strict={strict}) lost an entry"),
+ Err(err) => panic!("conforming {name} entries should parse (strict={strict}): {err:?}"),
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn xref_subsection_start_near_usize_max_is_skipped() {
+ // A subsection header's start is read straight from the file, so it is untrusted.
+ // A start of usize::MAX made `start + index` overflow: a panic wherever overflow
+ // checks are on (a denial of service for any consumer parsing untrusted PDFs), and
+ // a silent wrap to object 0 where they are not.
+ let input = &b"xref\n18446744073709551615 2\n0000000000 65535 f \n0000000009 00000 n \ntrailer\n<</Size 2/Root 1 0 R>>\n"[..];
+ for strict in [false, true] {
+ match xref(test_span(input), strict) {
+ Ok((_, re)) => assert!(
+ re.entries.is_empty(),
+ "unrepresentable object number was inserted (strict={strict}): {:?}",
+ re.entries
+ ),
+ Err(err) => panic!("xref should still parse (strict={strict}): {err:?}"),
+ }
+ }
+ }
+
+ #[test]
+ fn xref_subsection_start_beyond_u32_does_not_displace_entries() {
+ // Object numbers are u32, but the subsection start is parsed as usize and was cast
+ // with `as u32`. A start above u32::MAX truncated into a valid-looking number --
+ // 4294967297 becomes 1 -- silently overwriting a legitimate entry with an arbitrary
+ // offset. No overflow occurs here, so a checked add alone would not catch it.
+ let input = &b"xref\n0 2\n0000000000 65535 f \n0000000009 00000 n \n4294967297 1\n0000000999 00000 n \ntrailer\n<</Size 2/Root 1 0 R>>\n"[..];
+ for strict in [false, true] {
+ match xref(test_span(input), strict) {
+ Ok((_, re)) => {
+ assert_eq!(
+ re.entries.len(),
+ 1,
+ "(strict={strict}) unexpected entries: {:?}",
+ re.entries
+ );
+ assert!(
+ matches!(
+ re.get(1),
+ Some(XrefEntry::Normal {
+ offset: 9,
+ generation: 0
+ })
+ ),
+ "entry for object 1 was displaced (strict={strict}): {:?}",
+ re.get(1)
+ );
+ }
+ Err(err) => panic!("xref should still parse (strict={strict}): {err:?}"),
+ }
+ }
+ }
+
+ #[test]
+ fn startxref_trailing_space_after_keyword() {
+ // Some PDF generators emit "startxref \n" with a trailing space.
+ let input = b"startxref \n135738\n%%EOF\n";
+ match xref_start(test_span(input)) {
+ Some(num) => assert_eq!(num, 135738),
+ None => panic!("startxref with trailing space should parse"),
+ }
+ }
+
+ #[test]
+ fn content_silently_truncates_corrupted_data() {
+ // Corrupted data with unterminated string literal
+ let data = b"q 1 0 0 1 10 10 cm (corrupted Q";
+
+ let content = content(data).unwrap();
+
+ // Operations before the corruption returned without an error.
+ // Trailing Q was silently dropped.
+ assert_eq!(content.operations.len(), 2);
+ assert_eq!(content.operations[0].operator, "q");
+ assert_eq!(content.operations[1].operator, "cm");
+ }
+
+ #[test]
+ fn content_strict_rejects_corrupted_data() {
+ let data = b"q 1 0 0 1 10 10 cm (corrupted Q";
+ assert!(content_strict(data).is_err());
+ }
+
+ fn on_big_stack(f: impl FnOnce() + Send + 'static) {
+ std::thread::Builder::new()
+ .stack_size(64 * 1024 * 1024)
+ .spawn(f)
+ .unwrap()
+ .join()
+ .unwrap();
+ }
+
+ #[test]
+ fn deeply_nested_array_is_rejected() {
+ on_big_stack(|| {
+ let depth = 200_000;
+ let mut input = Vec::with_capacity(depth * 2);
+ input.extend(std::iter::repeat_n(b'[', depth));
+ input.extend(std::iter::repeat_n(b']', depth));
+ let result = _direct_object(crate::reader::MAX_NESTING_DEPTH)(input.as_slice());
+ assert!(result.is_err());
+ });
+ }
+
+ #[test]
+ fn deeply_nested_dictionary_is_rejected() {
+ on_big_stack(|| {
+ let depth = 200_000;
+ let mut input = Vec::with_capacity(depth * 6);
+ for _ in 0..depth {
+ input.extend_from_slice(b"<</K ");
+ }
+ for _ in 0..depth {
+ input.extend_from_slice(b">>");
+ }
+ let result = _direct_object(crate::reader::MAX_NESTING_DEPTH)(input.as_slice());
+ assert!(result.is_err());
+ });
+ }
+
+ #[test]
+ fn modestly_nested_array_still_parses() {
+ let input = b"[[[[[1]]]]]";
+ let obj = _direct_object(crate::reader::MAX_NESTING_DEPTH)(test_span(input));
+ assert!(obj.is_ok());
+ }
+}
diff --git a/vendor/lopdf/src/parser_aux.rs b/vendor/lopdf/src/parser_aux.rs
new file mode 100644
index 000000000..5e2f12b31
--- /dev/null
+++ b/vendor/lopdf/src/parser_aux.rs
@@ -0,0 +1,947 @@
+use log::warn;
+
+use crate::{Dictionary, Object, ObjectId, Stream, parser};
+use crate::{
+ Error, Result,
+ content::{Content, Operation},
+ document::Document,
+ encodings::Encoding,
+ error::ParseError,
+ object::Object::Name,
+ xref::{Xref, XrefEntry, XrefType},
+};
+use std::{
+ collections::BTreeMap,
+ io::{Cursor, Read},
+};
+
+impl Content<Vec<Operation>> {
+ /// Decode content operations.
+ pub fn decode(data: &[u8]) -> Result<Self> {
+ parser::content(data).ok_or(ParseError::InvalidContentStream.into())
+ }
+
+ /// Strict decode content operations.
+ pub fn decode_strict(data: &[u8]) -> Result<Self> {
+ parser::content_strict(data).map_err(|e| e.into())
+ }
+}
+
+impl Stream {
+ /// Decode content after decoding all stream filters.
+ pub fn decode_content(&self) -> Result<Content<Vec<Operation>>> {
+ Content::decode(&self.content)
+ }
+}
+
+impl Document {
+ /// Get decoded page content;
+ pub fn get_and_decode_page_content(&self, page_id: ObjectId) -> Result<Content<Vec<Operation>>> {
+ let content_data = self.get_page_content(page_id);
+ Content::decode(&content_data)
+ }
+
+ /// Add content to a page. All existing content will be unchanged.
+ pub fn add_to_page_content(&mut self, page_id: ObjectId, content: Content<Vec<Operation>>) -> Result<()> {
+ let content_data = Content::encode(&content)?;
+ self.add_page_contents(page_id, content_data)?;
+ Ok(())
+ }
+
+ pub fn extract_text(&self, page_numbers: &[u32]) -> Result<String> {
+ self.extract_text_inner(page_numbers, None)
+ }
+
+ /// Extract text from the given pages, bounding the total decompressed content
+ /// of each page to `max_decompressed_size` bytes.
+ ///
+ /// This is the decompression-bomb-safe counterpart to
+ /// [`Document::extract_text`]: page content is decoded via
+ /// [`Document::get_page_content_with_limit`], so a small compressed content
+ /// stream cannot inflate without limit. Prefer it over [`Document::extract_text`]
+ /// for PDFs from an untrusted source. Returns
+ /// [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded)
+ /// if any requested page's content would exceed the limit.
+ pub fn extract_text_with_limit(&self, page_numbers: &[u32], max_decompressed_size: usize) -> Result<String> {
+ self.extract_text_inner(page_numbers, Some(max_decompressed_size))
+ }
+
+ fn extract_text_inner(&self, page_numbers: &[u32], limit: Option<usize>) -> Result<String> {
+ let text_fragments = self.extract_text_chunks_inner(page_numbers, limit);
+ let mut text = String::new();
+ for maybe_text_fragment in text_fragments.into_iter() {
+ let text_fragment = maybe_text_fragment?;
+ text.push_str(&text_fragment);
+ }
+
+ Ok(text)
+ }
+
+ pub fn extract_text_chunks(&self, page_numbers: &[u32]) -> Vec<Result<String>> {
+ self.extract_text_chunks_inner(page_numbers, None)
+ }
+
+ /// Bomb-safe counterpart to [`Document::extract_text_chunks`], bounding the
+ /// total decompressed content of each page to `max_decompressed_size` bytes.
+ /// A page whose content exceeds the limit yields an `Err` chunk carrying
+ /// [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded).
+ pub fn extract_text_chunks_with_limit(
+ &self, page_numbers: &[u32], max_decompressed_size: usize,
+ ) -> Vec<Result<String>> {
+ self.extract_text_chunks_inner(page_numbers, Some(max_decompressed_size))
+ }
+
+ fn extract_text_chunks_inner(&self, page_numbers: &[u32], limit: Option<usize>) -> Vec<Result<String>> {
+ let pages: BTreeMap<u32, (u32, u16)> = self.get_pages();
+ page_numbers
+ .iter()
+ .flat_map(|page_number| {
+ let result = self.extract_text_chunks_from_page(&pages, *page_number, limit);
+ match result {
+ Ok(text_chunks) => text_chunks,
+ Err(err) => vec![Err(err)],
+ }
+ })
+ .collect()
+ }
+
+ fn extract_text_chunks_from_page(
+ &self, pages: &BTreeMap<u32, (u32, u16)>, page_number: u32, limit: Option<usize>,
+ ) -> Result<Vec<Result<String>>> {
+ let mut collected_chunks_and_errs: Vec<std::result::Result<String, Error>> = Vec::new();
+
+ let page_id = *pages.get(&page_number).ok_or(Error::PageNumberNotFound(page_number))?;
+ let fonts = self.get_page_fonts(page_id)?;
+ let encodings: BTreeMap<Vec<u8>, Encoding> = fonts
+ .into_iter()
+ .filter_map(|(name, font)| {
+ let encoding = match limit {
+ Some(max) => font.get_font_encoding_with_limit(self, max),
+ None => font.get_font_encoding(self),
+ };
+ match encoding {
+ Ok(it) => Some((name, it)),
+ Err(err) => {
+ collected_chunks_and_errs.push(Err(err));
+ None
+ }
+ }
+ })
+ .collect();
+ let content_data = match limit {
+ Some(max) => self.get_page_content_with_limit(page_id, max)?,
+ None => self.get_page_content(page_id),
+ };
+ let content = Content::decode(&content_data)?;
+
+ // each text with different encoding is extracted as separate chunk
+ let mut current_encoding = None;
+ let mut current_text = String::new();
+ for operation in &content.operations {
+ match operation.operator.as_ref() {
+ "Tf" => {
+ let current_font = operation
+ .operands
+ .first()
+ .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
+ .as_name();
+ current_encoding = match current_font {
+ Ok(font) => encodings.get(font),
+ Err(err) => {
+ collected_chunks_and_errs.push(Err(err));
+ None
+ }
+ };
+
+ if !current_text.is_empty() {
+ collected_chunks_and_errs.push(Ok(current_text));
+ current_text = String::new();
+ }
+ }
+ "Tj" | "TJ" => match current_encoding {
+ Some(encoding) => {
+ let res = collect_text(&mut current_text, encoding, &operation.operands);
+ if let Err(err) = res {
+ collected_chunks_and_errs.push(Err(err));
+ }
+ }
+ None => warn!("Could not decode extracted text"),
+ },
+ // PDF 32000-1 §9.4.3 — `'` is equivalent to `T* Tj`:
+ // move to next line, then show string from the single
+ // string operand.
+ "'" => match current_encoding {
+ Some(encoding) => {
+ if !current_text.ends_with('\n') {
+ current_text.push('\n');
+ }
+ let res = collect_text(&mut current_text, encoding, &operation.operands);
+ if let Err(err) = res {
+ collected_chunks_and_errs.push(Err(err));
+ }
+ }
+ None => warn!("Could not decode extracted text"),
+ },
+ // PDF 32000-1 §9.4.3 — `"` is equivalent to
+ // `aw Tw ac Tc T* Tj` with operands `[aw, ac, string]`.
+ // Operands 0/1 set word/character spacing for rendering
+ // and don't affect the extracted character sequence;
+ // operand 2 is the string to show.
+ "\"" => match current_encoding {
+ Some(encoding) => {
+ if !current_text.ends_with('\n') {
+ current_text.push('\n');
+ }
+ if let Some(string_operand) = operation.operands.get(2) {
+ let res = collect_text(&mut current_text, encoding, std::slice::from_ref(string_operand));
+ if let Err(err) = res {
+ collected_chunks_and_errs.push(Err(err));
+ }
+ }
+ }
+ None => warn!("Could not decode extracted text"),
+ },
+ // PDF 32000-1 §9.4.2 — `T*` moves to the start of the
+ // next line. For text extraction we approximate this
+ // as `\n`, matching how the `ET` arm above handles end
+ // of text object.
+ "T*" if !current_text.ends_with('\n') => current_text.push('\n'),
+ "T*" => {}
+ "ET" if !current_text.ends_with('\n') => current_text.push('\n'),
+ "ET" => {}
+ _ => {}
+ }
+ }
+ if !current_text.is_empty() {
+ collected_chunks_and_errs.push(Ok(current_text));
+ }
+
+ Ok(collected_chunks_and_errs)
+ }
+
+ pub fn replace_text(
+ &mut self, page_number: u32, text: &str, other_text: &str, default_str: Option<&str>,
+ ) -> Result<()> {
+ let page = page_number.saturating_sub(1) as usize;
+ let page_id = self
+ .page_iter()
+ .nth(page)
+ .ok_or(Error::PageNumberNotFound(page_number))?;
+ let encodings: BTreeMap<Vec<u8>, Encoding> = self
+ .get_page_fonts(page_id)?
+ .into_iter()
+ .map(|(name, font)| font.get_font_encoding(self).map(|it| (name, it)))
+ .collect::<Result<BTreeMap<Vec<u8>, Encoding>>>()?;
+ let content_data = self.get_page_content(page_id);
+ let mut content = Content::decode(&content_data)?;
+ let mut current_encoding = None;
+ for operation in &mut content.operations {
+ match operation.operator.as_ref() {
+ "Tf" => {
+ let current_font = operation
+ .operands
+ .first()
+ .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
+ .as_name()?;
+ current_encoding = encodings.get(current_font);
+ }
+ "Tj" | "TJ" => match current_encoding {
+ Some(encoding) => {
+ try_to_replace_encoded_text(operation, encoding, text, other_text, default_str.unwrap_or(""))?
+ }
+ None => {
+ warn!("Could not decode extracted text, some of the occurances might not be properly replaced")
+ }
+ },
+ _ => {}
+ }
+ }
+ let modified_content = content.encode()?;
+ self.change_page_content(page_id, modified_content)
+ }
+
+ pub fn replace_partial_text(
+ &mut self, page_number: u32, search_text: &str, replacement_text: &str, default_char: Option<&str>,
+ ) -> Result<usize> {
+ let page = page_number.saturating_sub(1) as usize;
+ let page_id = self
+ .page_iter()
+ .nth(page)
+ .ok_or(Error::PageNumberNotFound(page_number))?;
+
+ let encodings: BTreeMap<Vec<u8>, Encoding> = self
+ .get_page_fonts(page_id)?
+ .into_iter()
+ .map(|(name, font)| font.get_font_encoding(self).map(|it| (name, it)))
+ .collect::<Result<BTreeMap<Vec<u8>, Encoding>>>()?;
+
+ let content_data = self.get_page_content(page_id);
+ let mut content = Content::decode(&content_data)?;
+ let mut current_encoding = None;
+ let mut replacement_count = 0;
+
+ for operation in &mut content.operations {
+ match operation.operator.as_ref() {
+ "Tf" => {
+ let current_font = operation
+ .operands
+ .first()
+ .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
+ .as_name()?;
+ current_encoding = encodings.get(current_font);
+ }
+ "Tj" | "TJ" => {
+ if let Some(encoding) = current_encoding {
+ replacement_count += replace_partial_in_operation(
+ operation,
+ encoding,
+ search_text,
+ replacement_text,
+ default_char.unwrap_or("?"),
+ )?;
+ } else {
+ warn!("No encoding found for text operation");
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if replacement_count > 0 {
+ let modified_content = content.encode()?;
+ self.change_page_content(page_id, modified_content)?;
+ }
+
+ Ok(replacement_count)
+ }
+
+ pub fn insert_image(
+ &mut self, page_id: ObjectId, img_object: Stream, position: (f32, f32), size: (f32, f32),
+ ) -> Result<()> {
+ let img_id = self.add_object(img_object);
+ let img_name = format!("X{}", img_id.0);
+
+ self.add_xobject(page_id, img_name.as_bytes(), img_id)?;
+
+ let mut content = self.get_and_decode_page_content(page_id)?;
+ content.operations.push(Operation::new("q", vec![]));
+ content.operations.push(Operation::new(
+ "cm",
+ vec![
+ size.0.into(),
+ 0.into(),
+ 0.into(),
+ size.1.into(),
+ position.0.into(),
+ position.1.into(),
+ ],
+ ));
+ content
+ .operations
+ .push(Operation::new("Do", vec![Name(img_name.as_bytes().to_vec())]));
+ content.operations.push(Operation::new("Q", vec![]));
+
+ self.change_page_content(page_id, content.encode()?)
+ }
+
+ pub fn insert_form_object(&mut self, page_id: ObjectId, form_obj: Stream) -> Result<()> {
+ let form_id = self.add_object(form_obj);
+ let form_name = format!("X{}", form_id.0);
+
+ let mut content = self.get_and_decode_page_content(page_id)?;
+ content.operations.insert(0, Operation::new("q", vec![]));
+ content.operations.push(Operation::new("Q", vec![]));
+ content
+ .operations
+ .push(Operation::new("Do", vec![Name(form_name.as_bytes().to_vec())]));
+ let modified_content = content.encode()?;
+ self.add_xobject(page_id, form_name, form_id)?;
+
+ self.change_page_content(page_id, modified_content)
+ }
+}
+fn collect_text(text: &mut String, encoding: &Encoding, operands: &[Object]) -> Result<()> {
+ for operand in operands.iter() {
+ match operand {
+ Object::String(bytes, _) => {
+ encoding.write_to_string(bytes, text)?;
+ }
+ Object::Array(arr) => {
+ collect_text(text, encoding, arr)?;
+ text.push(' ');
+ }
+ Object::Integer(i) if *i < -100 => {
+ text.push(' ');
+ }
+ _ => {}
+ }
+ }
+ Ok(())
+}
+pub fn substr(s: &str, start: usize, len: usize) -> &str {
+ let mut indices = s.char_indices();
+
+ for _ in 0..start {
+ if indices.next().is_none() {
+ return "";
+ }
+ }
+
+ let Some((start_idx, _)) = indices.next() else {
+ return "";
+ };
+
+ let end_idx = indices
+ .nth(len.saturating_sub(1))
+ .map(|(idx, _)| idx)
+ .unwrap_or(s.len());
+
+ &s[start_idx..end_idx]
+}
+pub fn substring(s: &str, start: usize) -> &str {
+ s.char_indices().nth(start).map(|(idx, _)| &s[idx..]).unwrap_or("")
+}
+
+fn encode(encoding: &Encoding, txt: &str, default_str: &str) -> Vec<u8> {
+ if txt.chars().count() > 1 {
+ let mut cur = 0;
+ let mut result = Vec::new();
+ while cur < txt.chars().count() {
+ let c = substr(txt, cur, 1);
+ result.extend_from_slice(&encode(encoding, c, default_str));
+ cur += 1;
+ }
+ result
+ } else {
+ let encoded_bytes = Document::encode_text(encoding, txt);
+ if !encoded_bytes.is_empty() {
+ encoded_bytes
+ } else {
+ Document::encode_text(encoding, default_str)
+ }
+ }
+}
+fn try_to_replace_encoded_text(
+ operation: &mut Operation, encoding: &Encoding, text_to_replace: &str, replacement: &str, default_str: &str,
+) -> Result<()> {
+ for operand in &mut operation.operands {
+ match operand {
+ Object::String(bytes, _) => {
+ let decoded_text = Document::decode_text(encoding, bytes)?;
+ if decoded_text == text_to_replace {
+ let encoded_bytes = encode(encoding, replacement, default_str);
+ *bytes = encoded_bytes;
+ }
+ }
+ Object::Array(arr) => {
+ let mut str_collected = String::new();
+ collect_text(&mut str_collected, encoding, arr)?;
+ if str_collected == text_to_replace {
+ // The number of `Object::String` items in a `TJ` array is
+ // not guaranteed to match the character count of the
+ // decoded text (each string may hold several glyphs, and
+ // numeric kerning entries are interleaved).
+ //
+ // There is no **good** way to interpolate between the OG
+ // and the replacement, but putting the full encoded replacement
+ // into the first string slot and emptying out the remaining
+ // string slots, leaving any numeric kerning entries in place
+ // seems like the least bad option.
+ let encoded_replacement = encode(encoding, replacement, default_str);
+ let mut placed = false;
+ for item in arr.iter_mut() {
+ if let Object::String(bytes, _f) = item {
+ if placed {
+ *bytes = Vec::new();
+ } else {
+ bytes.clone_from(&encoded_replacement);
+ placed = true;
+ }
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ Ok(())
+}
+
+fn replace_partial_in_operation(
+ operation: &mut Operation, encoding: &Encoding, search_text: &str, replacement_text: &str, default_char: &str,
+) -> Result<usize> {
+ let mut replacement_count = 0;
+
+ for operand in &mut operation.operands {
+ match operand {
+ Object::String(bytes, _) => {
+ let decoded_text = Document::decode_text(encoding, bytes)?;
+ if decoded_text.contains(search_text) {
+ let new_text = decoded_text.replace(search_text, replacement_text);
+ let encoded_bytes = encode_with_fallback(encoding, &new_text, default_char);
+ *bytes = encoded_bytes;
+ replacement_count += decoded_text.matches(search_text).count();
+ }
+ }
+ Object::Array(arr) => {
+ replacement_count +=
+ replace_partial_in_array(arr, encoding, search_text, replacement_text, default_char)?;
+ }
+ _ => {}
+ }
+ }
+
+ Ok(replacement_count)
+}
+
+fn replace_partial_in_array(
+ arr: &mut [Object], encoding: &Encoding, search_text: &str, replacement_text: &str, default_char: &str,
+) -> Result<usize> {
+ let mut replacement_count = 0;
+
+ for item in arr.iter_mut() {
+ if let Object::String(bytes, _) = item {
+ let decoded_text = Document::decode_text(encoding, bytes)?;
+ if decoded_text.contains(search_text) {
+ let new_text = decoded_text.replace(search_text, replacement_text);
+ let encoded_bytes = encode_with_fallback(encoding, &new_text, default_char);
+ *bytes = encoded_bytes;
+ replacement_count += decoded_text.matches(search_text).count();
+ }
+ }
+ }
+
+ Ok(replacement_count)
+}
+
+fn encode_with_fallback(encoding: &Encoding, text: &str, default_char: &str) -> Vec<u8> {
+ let encoded = Document::encode_text(encoding, text);
+ if !encoded.is_empty() {
+ return encoded;
+ }
+
+ encode(encoding, text, default_char)
+}
+
+/// Decode CrossReferenceStream
+pub fn decode_xref_stream(stream: Stream) -> Result<(Xref, Dictionary)> {
+ decode_xref_stream_with_limit(stream, None)
+}
+
+/// Decode a cross-reference stream, rejecting it if its decompressed content
+/// would exceed `max_decompressed_size` bytes. `None` means no limit (the
+/// behavior of [`decode_xref_stream`]). Cross-reference streams are decoded
+/// early during loading, so this bounds the memory a `/XRef` stream can use.
+pub fn decode_xref_stream_with_limit(
+ mut stream: Stream, max_decompressed_size: Option<usize>,
+) -> Result<(Xref, Dictionary)> {
+ if stream.is_compressed() {
+ match max_decompressed_size {
+ Some(max) => stream.decompress_with_limit(max)?,
+ None => stream.decompress()?,
+ }
+ }
+ let mut dict = stream.dict;
+ let mut reader = Cursor::new(stream.content);
+ let size = dict
+ .get(b"Size")
+ .and_then(Object::as_i64)
+ .map_err(|_| ParseError::InvalidXref)?;
+ let mut xref = Xref::new(size as u32, XrefType::CrossReferenceStream);
+ {
+ let section_indice = dict
+ .get(b"Index")
+ .and_then(parse_integer_array)
+ .unwrap_or_else(|_| vec![0, size]);
+ let field_widths = dict
+ .get(b"W")
+ .and_then(parse_integer_array)
+ .map_err(|_| ParseError::InvalidXref)?;
+
+ // Each width is a byte count for one xref-stream field. The PDF spec doesn't need more than a
+ // few bytes per field (8 covers the full u64/i64 range); bound them before sizing a Vec from
+ // them, or a crafted stream can request an allocation of up to (2^64-1) bytes per field.
+ const MAX_XREF_FIELD_WIDTH: i64 = 8;
+ if field_widths.len() < 3
+ || field_widths[0].is_negative()
+ || field_widths[1].is_negative()
+ || field_widths[2].is_negative()
+ || field_widths[0] > MAX_XREF_FIELD_WIDTH
+ || field_widths[1] > MAX_XREF_FIELD_WIDTH
+ || field_widths[2] > MAX_XREF_FIELD_WIDTH
+ {
+ return Err(ParseError::InvalidXref.into());
+ }
+
+ // Total bytes one entry consumes. With every width zero an entry reads nothing, so the loop
+ // below would run purely on the attacker-controlled /Index counts and never reach the end of
+ // the stream. Such a stream carries no information and can only be malformed, so reject it
+ // (this also keeps the body-capacity check below from dividing by zero).
+ let entry_width = (field_widths[0] + field_widths[1] + field_widths[2]) as usize;
+ if entry_width == 0 {
+ return Err(ParseError::InvalidXref.into());
+ }
+
+ let index_entries = section_indice
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .try_fold(0_usize, |total, section| {
+ let count = usize::try_from(section[1]).map_err(|_| ParseError::InvalidXref)?;
+ total.checked_add(count).ok_or(ParseError::InvalidXref)
+ })?;
+ // An entry can't be read from bytes that aren't there. Validate the total before inserting
+ // anything so multiple individually plausible /Index sections cannot overrun the body.
+ //
+ // deliberate: Records narrower than three bytes are rejected to limit amplification from
+ // decoded bytes into retained map entries. /W [1 2 0] is a plausible three-byte record and
+ // remains accepted; lopdf's writer emits /W [1 4 2], so its output is unaffected.
+ const MIN_ENTRY_WIDTH: usize = 3;
+ if index_entries > reader.get_ref().len() / entry_width.max(MIN_ENTRY_WIDTH) {
+ return Err(ParseError::InvalidXref.into());
+ }
+
+ let mut bytes1 = vec![0_u8; field_widths[0] as usize];
+ let mut bytes2 = vec![0_u8; field_widths[1] as usize];
+ let mut bytes3 = vec![0_u8; field_widths[2] as usize];
+
+ for section in section_indice.as_chunks::<2>().0 {
+ let start = section[0];
+ let count = section[1];
+
+ for j in 0..count {
+ let entry_type = if !bytes1.is_empty() {
+ read_big_endian_integer(&mut reader, bytes1.as_mut_slice())?
+ } else {
+ 1
+ };
+ match entry_type {
+ 0 => {
+ // free object
+ read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
+ read_big_endian_integer(&mut reader, bytes3.as_mut_slice())?;
+ }
+ 1 => {
+ // normal object
+ let offset = read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
+ let generation = if !bytes3.is_empty() {
+ read_big_endian_integer(&mut reader, bytes3.as_mut_slice())?
+ } else {
+ 0
+ } as u16;
+ xref.insert((start + j) as u32, XrefEntry::Normal { offset, generation });
+ }
+ 2 => {
+ // compressed object
+ let container = read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
+ let index = read_big_endian_integer(&mut reader, bytes3.as_mut_slice())? as u16;
+ xref.insert((start + j) as u32, XrefEntry::Compressed { container, index });
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ dict.remove(b"Length");
+ dict.remove(b"W");
+ dict.remove(b"Index");
+ Ok((xref, dict))
+}
+
+fn read_big_endian_integer(reader: &mut Cursor<Vec<u8>>, buffer: &mut [u8]) -> Result<u32> {
+ reader.read_exact(buffer)?;
+ let mut value = 0;
+ for &mut byte in buffer {
+ value = (value << 8) + u32::from(byte);
+ }
+ Ok(value)
+}
+
+fn parse_integer_array(array: &Object) -> Result<Vec<i64>> {
+ let array = array.as_array()?;
+ let mut out = Vec::with_capacity(array.len());
+
+ for n in array {
+ out.push(n.as_i64()?);
+ }
+
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ #[cfg(not(feature = "async"))]
+ #[test]
+ fn load_and_save() {
+ use crate::Document;
+ use crate::creator::tests::{create_document, save_document};
+
+ // test load_from() and save_to()
+ use std::fs::File;
+ use std::io::Cursor;
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir().unwrap();
+ let file_path = temp_dir.path().join("test_1_load_and_save.pdf");
+
+ let mut doc = create_document();
+
+ save_document(&file_path, &mut doc);
+
+ let in_file = File::open(file_path).unwrap();
+ let mut in_doc = Document::load_from(in_file).unwrap();
+
+ let out_buf = Vec::new();
+ let mut memory_cursor = Cursor::new(out_buf);
+ in_doc.save_to(&mut memory_cursor).unwrap();
+ // Check if saved file is not an empty bytes vector.
+ assert!(!memory_cursor.get_ref().is_empty());
+ }
+
+ #[test]
+ fn extract_text_chunks() {
+ use crate::creator::tests::create_document_with_texts;
+
+ let text1 = "Hello world!";
+ let text2 = "Ferris is the best!";
+ let doc = create_document_with_texts(&[text1, text2]);
+ let extracted_texts = doc.extract_text_chunks(&[1, 2]);
+ assert_eq!(extracted_texts.len(), 2);
+ assert_eq!(
+ [
+ extracted_texts[0].as_ref().unwrap().trim(),
+ extracted_texts[1].as_ref().unwrap().trim()
+ ],
+ [text1, text2]
+ );
+ }
+
+ #[test]
+ fn extract_text_concatenates_text_from_multiple_pages() {
+ use crate::creator::tests::create_document_with_texts;
+
+ let text1 = "Hello world!";
+ let text2 = "Ferris is the best!";
+ let doc = create_document_with_texts(&[text1, text2]);
+ let extracted_text = doc.extract_text(&[1, 2]);
+ assert_eq!(extracted_text.unwrap(), format!("{text1}\n{text2}\n"));
+ }
+
+ const BOMB_MIB: usize = 1024 * 1024;
+
+ /// A FlateDecode-compressed stream that inflates to `target` zero-bytes, built
+ /// by streaming zeros through the compressor so the test process never holds
+ /// `target` bytes at once.
+ fn flate_bomb(target: usize) -> Vec<u8> {
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+ use std::io::Write;
+
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ let zeros = [0u8; 64 * 1024];
+ let mut remaining = target;
+ while remaining > 0 {
+ let n = remaining.min(zeros.len());
+ encoder.write_all(&zeros[..n]).unwrap();
+ remaining -= n;
+ }
+ encoder.finish().unwrap()
+ }
+
+ /// A `create_document_with_texts` document whose first page's content stream
+ /// has been swapped for a FlateDecode bomb that inflates to `target` bytes.
+ fn doc_with_page_content_bomb(target: usize) -> crate::Document {
+ use crate::{Dictionary, Object, Stream};
+
+ let mut doc = create_document_with_texts(&["Hello"]);
+ let page_id = *doc.get_pages().get(&1).expect("page 1 exists");
+ let content_id = doc.get_page_contents(page_id)[0];
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "FlateDecode");
+ doc.objects
+ .insert(content_id, Object::Stream(Stream::new(dict, flate_bomb(target))));
+ doc
+ }
+
+ /// A `create_document_with_texts` document whose font carries a `/ToUnicode`
+ /// CMap that is a FlateDecode bomb. Font encodings are resolved (and thus this
+ /// stream is decoded) during text extraction, *before* the page content — so
+ /// this exercises a decompression vector distinct from page content.
+ fn doc_with_tounicode_font_bomb(target: usize) -> crate::Document {
+ use crate::{Dictionary, Object, Stream};
+
+ let mut doc = create_document_with_texts(&["Hello"]);
+ let font_id = doc
+ .objects
+ .iter()
+ .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
+ .map(|(id, _)| *id)
+ .expect("font object exists");
+
+ let mut tounicode_dict = Dictionary::new();
+ tounicode_dict.set("Filter", "FlateDecode");
+ let tounicode_id = doc.add_object(Object::Stream(Stream::new(tounicode_dict, flate_bomb(target))));
+
+ let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
+ font.set("ToUnicode", Object::Reference(tounicode_id));
+ doc
+ }
+
+ use crate::creator::tests::create_document_with_texts;
+
+ /// Under a generous limit, `extract_text_with_limit` returns exactly the same
+ /// text as the unbounded `extract_text`.
+ #[test]
+ fn extract_text_with_limit_matches_unbounded_under_limit() {
+ use crate::creator::tests::create_document_with_texts;
+
+ let text1 = "Hello world!";
+ let text2 = "Ferris is the best!";
+ let doc = create_document_with_texts(&[text1, text2]);
+
+ let bounded = doc.extract_text_with_limit(&[1, 2], BOMB_MIB).unwrap();
+ let unbounded = doc.extract_text(&[1, 2]).unwrap();
+ assert_eq!(bounded, unbounded);
+ }
+
+ /// A page-content decompression bomb is rejected end-to-end by
+ /// `extract_text_with_limit` instead of inflating without bound.
+ #[test]
+ fn extract_text_with_limit_rejects_page_content_bomb() {
+ use crate::{DecompressError, Error};
+
+ let doc = doc_with_page_content_bomb(32 * BOMB_MIB);
+
+ match doc.extract_text_with_limit(&[1], 4 * BOMB_MIB).map(|s| s.len()) {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, 4 * BOMB_MIB);
+ }
+ other => panic!("expected MemoryLimitExceeded, got {other:?}"),
+ }
+ }
+
+ /// The chunked variant surfaces the same bomb as an `Err` chunk rather than
+ /// panicking or silently truncating.
+ #[test]
+ fn extract_text_chunks_with_limit_surfaces_limit_error() {
+ use crate::{DecompressError, Error};
+
+ let doc = doc_with_page_content_bomb(32 * BOMB_MIB);
+ let chunks = doc.extract_text_chunks_with_limit(&[1], 4 * BOMB_MIB);
+
+ assert!(
+ chunks.iter().any(|chunk| matches!(
+ chunk,
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { .. }))
+ )),
+ "expected a MemoryLimitExceeded error chunk"
+ );
+ }
+
+ /// A bomb reached through a font's `/ToUnicode` CMap (decoded during encoding
+ /// resolution, before page content) is also bounded by `extract_text_with_limit`
+ /// — otherwise the "safe for untrusted input" guarantee has a hole.
+ #[test]
+ fn extract_text_with_limit_rejects_tounicode_font_bomb() {
+ use crate::{DecompressError, Error};
+
+ let doc = doc_with_tounicode_font_bomb(32 * BOMB_MIB);
+
+ match doc.extract_text_with_limit(&[1], 4 * BOMB_MIB).map(|s| s.len()) {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, 4 * BOMB_MIB);
+ }
+ other => panic!("expected MemoryLimitExceeded from ToUnicode font bomb, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn test_replace_partial_text() {
+ use crate::creator::tests::create_document_with_texts;
+
+ let mut doc = create_document_with_texts(&["Hello World! Hello Universe!"]);
+ let replacements = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
+ assert_eq!(replacements, 2); // Should replace both occurrences
+
+ let extracted_text = doc.extract_text(&[1]).unwrap();
+ assert!(extracted_text.contains("Hi World! Hi Universe!"));
+ }
+
+ /// PDF 1.7 / ISO 32000-1 §9.4.3 — `'` is equivalent to `T* Tj`:
+ /// move to the next line and show a string. extract_text should
+ /// recover the string operand and emit a line break before it.
+ #[test]
+ fn extract_text_handles_apostrophe_show_text_op() {
+ use crate::Object;
+ use crate::content::Operation;
+ use crate::creator::tests::create_document_with_operations;
+
+ let doc = create_document_with_operations(vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![100.into(), 700.into()]),
+ Operation::new("Tj", vec![Object::string_literal("first")]),
+ Operation::new("'", vec![Object::string_literal("second")]),
+ Operation::new("'", vec![Object::string_literal("third")]),
+ Operation::new("ET", vec![]),
+ ]);
+
+ let text = doc.extract_text(&[1]).unwrap();
+ assert!(text.contains("first"), "Tj string lost: {text:?}");
+ assert!(text.contains("second"), "first ' string lost: {text:?}");
+ assert!(text.contains("third"), "second ' string lost: {text:?}");
+ }
+
+ /// PDF 1.7 / ISO 32000-1 §9.4.3 — `"` is equivalent to
+ /// `aw Tw ac Tc T* Tj` with operands `[aw, ac, string]`. extract_text
+ /// should recover operand index 2 (the string); operands 0 and 1 set
+ /// rendering spacing and don't affect the extracted character sequence.
+ #[test]
+ fn extract_text_handles_quote_show_text_op() {
+ use crate::Object;
+ use crate::content::Operation;
+ use crate::creator::tests::create_document_with_operations;
+
+ let doc = create_document_with_operations(vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![100.into(), 700.into()]),
+ Operation::new("\"", vec![0.into(), 0.into(), Object::string_literal("from-quote-op")]),
+ Operation::new("ET", vec![]),
+ ]);
+
+ let text = doc.extract_text(&[1]).unwrap();
+ assert!(text.contains("from-quote-op"), "\" string operand lost: {text:?}");
+ }
+
+ /// PDF 1.7 / ISO 32000-1 §9.4.2 — `T*` moves to the start of the
+ /// next line. For text extraction we approximate as `\n`, so a
+ /// `Tj T* Tj` sequence should produce two strings separated by a
+ /// newline rather than running together.
+ #[test]
+ fn extract_text_preserves_line_breaks_for_t_star() {
+ use crate::Object;
+ use crate::content::Operation;
+ use crate::creator::tests::create_document_with_operations;
+
+ let doc = create_document_with_operations(vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![100.into(), 700.into()]),
+ Operation::new("Tj", vec![Object::string_literal("line-one")]),
+ Operation::new("T*", vec![]),
+ Operation::new("Tj", vec![Object::string_literal("line-two")]),
+ Operation::new("ET", vec![]),
+ ]);
+
+ let text = doc.extract_text(&[1]).unwrap();
+ let one = text.find("line-one").expect("line-one missing");
+ let two = text.find("line-two").expect("line-two missing");
+ assert!(one < two, "order wrong: {text:?}");
+ let between = &text[one + "line-one".len()..two];
+ assert!(
+ between.contains('\n'),
+ "T* did not insert a line break between Tj strings: between={between:?}"
+ );
+ }
+}
diff --git a/vendor/lopdf/src/processor.rs b/vendor/lopdf/src/processor.rs
new file mode 100644
index 000000000..26107646b
--- /dev/null
+++ b/vendor/lopdf/src/processor.rs
@@ -0,0 +1,308 @@
+use crate::Result;
+use crate::{Document, Object, ObjectId};
+use std::collections::BTreeMap;
+use std::fs::File;
+use std::io::Write;
+
+impl Document {
+ /// Change producer of document information dictionary.
+ pub fn change_producer(&mut self, producer: &str) {
+ if let Ok(info) = self.trailer.get_mut(b"Info")
+ && let Some(dict) = match info {
+ Object::Dictionary(dict) => Some(dict),
+ Object::Reference(id) => self.objects.get_mut(id).and_then(|o| o.as_dict_mut().ok()),
+ _ => None,
+ }
+ {
+ dict.set("Producer", Object::string_literal(producer));
+ }
+ }
+
+ /// Compress PDF stream objects.
+ pub fn compress(&mut self) {
+ for object in self.objects.values_mut() {
+ if let Object::Stream(stream) = object
+ && stream.allows_compression
+ {
+ // Ignore any error and continue to compress other streams.
+ let _ = stream.compress();
+ }
+ }
+ }
+
+ /// Decompress PDF stream objects.
+ pub fn decompress(&mut self) {
+ for object in self.objects.values_mut() {
+ if let Object::Stream(stream) = object {
+ let _ = stream.decompress();
+ }
+ }
+ }
+
+ /// Delete pages.
+ pub fn delete_pages(&mut self, page_numbers: &[u32]) {
+ let pages = self.get_pages();
+ for page_number in page_numbers {
+ if let Some(page) = pages.get(page_number).and_then(|page_id| self.delete_object(*page_id)) {
+ let mut page_tree_ref = page
+ .as_dict()
+ .and_then(|dict| dict.get(b"Parent"))
+ .and_then(Object::as_reference);
+ while let Ok(page_tree_id) = page_tree_ref {
+ if let Some(page_tree) = self.objects.get_mut(&page_tree_id).and_then(|pt| pt.as_dict_mut().ok()) {
+ if let Ok(count) = page_tree.get(b"Count").and_then(Object::as_i64) {
+ page_tree.set("Count", count - 1);
+ }
+ page_tree_ref = page_tree.get(b"Parent").and_then(Object::as_reference);
+ } else {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ /// Prune all unused objects.
+ pub fn prune_objects(&mut self) -> Vec<ObjectId> {
+ let mut ids = vec![];
+ let refs = self.traverse_objects(|_| {});
+ for id in self.objects.keys() {
+ if !refs.contains(id) {
+ ids.push(*id);
+ }
+ }
+
+ for id in &ids {
+ self.objects.remove(id);
+ }
+
+ ids
+ }
+
+ /// Delete object by object ID.
+ pub fn delete_object(&mut self, id: ObjectId) -> Option<Object> {
+ let action = |object: &mut Object| match object {
+ Object::Array(array) => {
+ if let Some(index) = array.iter().position(|item: &Object| match *item {
+ Object::Reference(ref_id) => ref_id == id,
+ _ => false,
+ }) {
+ array.remove(index);
+ }
+ }
+ Object::Dictionary(dict) => {
+ let keys: Vec<Vec<u8>> = dict
+ .iter()
+ .filter(|&(_, item): &(&Vec<u8>, &Object)| match *item {
+ Object::Reference(ref_id) => ref_id == id,
+ _ => false,
+ })
+ .map(|(k, _)| k.clone())
+ .collect();
+ for key in keys {
+ dict.remove(&key);
+ }
+ }
+ _ => {}
+ };
+ self.traverse_objects(action);
+ self.objects.remove(&id)
+ }
+
+ /// Delete zero length stream objects.
+ pub fn delete_zero_length_streams(&mut self) -> Vec<ObjectId> {
+ let mut ids = vec![];
+ for id in self.objects.keys() {
+ if self
+ .objects
+ .get(id)
+ .and_then(|o| Object::as_stream(o).ok())
+ .map(|stream| stream.content.is_empty())
+ .unwrap_or(false)
+ {
+ ids.push(*id);
+ }
+ }
+
+ for id in &ids {
+ self.delete_object(*id);
+ }
+
+ ids
+ }
+
+ /// Renumber objects, normally called after delete_unused_objects.
+ pub fn renumber_objects(&mut self) {
+ self.renumber_objects_with(1)
+ }
+
+ fn update_bookmark_pages(&mut self, bookmarks: &[u32], old: &ObjectId, new: &ObjectId) {
+ for id in bookmarks {
+ let (children, page) = match self.bookmark_table.get(id) {
+ Some(n) => (n.children.clone(), n.page),
+ None => return,
+ };
+
+ if page == *old {
+ let bookmark = self.bookmark_table.get_mut(id).unwrap();
+ bookmark.page = *new;
+ }
+
+ if !children.is_empty() {
+ self.update_bookmark_pages(&children[..], old, new);
+ }
+ }
+ }
+
+ pub fn renumber_bookmarks(&mut self, old: &ObjectId, new: &ObjectId) {
+ if !self.bookmarks.is_empty() {
+ self.update_bookmark_pages(&self.bookmarks.clone(), old, new);
+ }
+ }
+
+ /// Renumber objects with a custom starting id, this is very useful in case of multiple
+ /// document object insertions in a single main document
+ pub fn renumber_objects_with(&mut self, starting_id: u32) {
+ let mut replace = BTreeMap::new();
+ let mut new_id = starting_id;
+ let mut i = 0;
+
+ // Check if we need to order the pages first, as this means the first page doesn't have a lower ID.
+ // So it ends up in a random spot based on its ID. We check first to avoid double traversal, unless we have too.
+
+ let mut page_order: Vec<(i32, (u32, u16))> = self
+ .page_iter()
+ .map(|id| {
+ i += 1;
+ (i, id)
+ })
+ .collect();
+
+ page_order.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
+
+ i = 0;
+
+ let needs_ordering = page_order.iter().any(|a| {
+ i += 1;
+ a.0 != i
+ });
+
+ if needs_ordering {
+ let mut pages = page_order.clone();
+ pages.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
+ let mut objects = BTreeMap::new();
+
+ for (old, new) in pages.iter().zip(page_order) {
+ if let Some(object) = self.objects.remove(&old.1) {
+ objects.insert((new.1.0, old.1.1), object);
+ replace.insert(old.1, (new.1.0, old.1.1));
+ }
+
+ if old.1 != new.1 {
+ self.renumber_bookmarks(&old.1, &(new.1.0, old.1.1));
+ }
+ }
+
+ for (new, object) in objects {
+ self.objects.insert(new, object);
+ }
+
+ let action = |object: &mut Object| {
+ if let Object::Reference(id) = object
+ && let Some(new_id) = replace.get(id)
+ {
+ *id = *new_id;
+ }
+ };
+
+ self.traverse_objects(action);
+ replace.clear();
+ }
+
+ let mut ids = self.objects.keys().cloned().collect::<Vec<ObjectId>>();
+ ids.sort_unstable();
+
+ for id in ids {
+ if id.0 != new_id {
+ replace.insert(id, (new_id, id.1));
+ }
+
+ new_id += 1;
+ }
+
+ let mut objects = BTreeMap::new();
+
+ // remove and collect all removed objects
+ for (old, new) in &replace {
+ if let Some(object) = self.objects.remove(old) {
+ objects.insert(*new, object);
+ }
+
+ if old != new {
+ self.renumber_bookmarks(old, new);
+ }
+ }
+
+ // insert new replaced keys objects
+ for (new, object) in objects {
+ self.objects.insert(new, object);
+ }
+
+ let action = |object: &mut Object| {
+ if let Object::Reference(id) = object
+ && let Some(new_id) = replace.get(id)
+ {
+ *id = *new_id;
+ }
+ };
+
+ self.traverse_objects(action);
+
+ self.max_id = new_id - 1;
+ }
+
+ pub fn change_content_stream(&mut self, stream_id: ObjectId, content: Vec<u8>) {
+ if let Some(Object::Stream(stream)) = self.objects.get_mut(&stream_id) {
+ stream.set_plain_content(content);
+ // Ignore any compression error.
+ let _ = stream.compress();
+ }
+ }
+
+ pub fn change_page_content(&mut self, page_id: ObjectId, content: Vec<u8>) -> Result<()> {
+ let contents = self.get_dictionary(page_id).and_then(|page| page.get(b"Contents"))?;
+ match contents {
+ Object::Reference(id) => self.change_content_stream(*id, content),
+ Object::Array(arr) => {
+ if arr.len() == 1 {
+ if let Ok(id) = arr[0].as_reference() {
+ self.change_content_stream(id, content)
+ }
+ } else {
+ let new_stream = self.add_object(super::Stream::new(dictionary! {}, content));
+ if let Ok(Object::Dictionary(dict)) = self.get_object_mut(page_id) {
+ dict.set("Contents", new_stream);
+ }
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ pub fn extract_stream(&self, stream_id: ObjectId, decompress: bool) -> Result<()> {
+ let mut file = File::create(format!("{stream_id:?}.bin"))?;
+ if let Ok(Object::Stream(stream)) = self.get_object(stream_id) {
+ if decompress {
+ if let Ok(data) = stream.decompressed_content() {
+ file.write_all(&data)?;
+ } else {
+ file.write_all(&stream.content)?;
+ }
+ } else {
+ file.write_all(&stream.content)?;
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/vendor/lopdf/src/reader.rs b/vendor/lopdf/src/reader.rs
new file mode 100644
index 000000000..e048e3acf
--- /dev/null
+++ b/vendor/lopdf/src/reader.rs
@@ -0,0 +1,1991 @@
+use log::{error, warn};
+use std::cmp;
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::convert::TryInto;
+#[cfg(not(feature = "async"))]
+use std::fs::File;
+#[cfg(not(feature = "async"))]
+use std::io::Read;
+use std::path::Path;
+use std::sync::Mutex;
+
+#[cfg(feature = "rayon")]
+use rayon::prelude::*;
+#[cfg(feature = "async")]
+use tokio::fs::File;
+#[cfg(feature = "async")]
+use tokio::io::{AsyncRead, AsyncReadExt};
+#[cfg(feature = "async")]
+use tokio::pin;
+
+use crate::common_data_structures;
+use crate::encryption::{self, EncryptionState};
+use crate::error::{ParseError, XrefError};
+use crate::load_options::{FilterFunc, LoadOptions};
+use crate::object_stream::ObjectStream;
+use crate::parser;
+use crate::xref::{Xref, XrefEntry, XrefType};
+use crate::{Dictionary, Document, Error, IncrementalDocument, Object, ObjectId, Result};
+
+#[cfg(not(feature = "async"))]
+impl Document {
+ /// Load a PDF document from a specified file path.
+ #[inline]
+ pub fn load<P: AsRef<Path>>(path: P) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::default())
+ }
+
+ /// Load a PDF document from a specified file path with the given options.
+ #[inline]
+ pub fn load_with_options<P: AsRef<Path>>(path: P, options: LoadOptions) -> Result<Document> {
+ let file = File::open(path)?;
+ let capacity = Some(file.metadata()?.len() as usize);
+ Self::load_internal(file, capacity, options)
+ }
+
+ /// Load a PDF document from a specified file path with a password for encrypted PDFs.
+ #[inline]
+ pub fn load_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::with_password(password))
+ }
+
+ #[deprecated(since = "0.41.0", note = "Use load_with_options instead")]
+ #[inline]
+ pub fn load_filtered<P: AsRef<Path>>(path: P, filter_func: FilterFunc) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::with_filter(filter_func))
+ }
+
+ /// Load a PDF document from an arbitrary source.
+ #[inline]
+ pub fn load_from<R: Read>(source: R) -> Result<Document> {
+ Self::load_from_with_options(source, LoadOptions::default())
+ }
+
+ /// Load a PDF document from an arbitrary source with the given options.
+ #[inline]
+ pub fn load_from_with_options<R: Read>(source: R, options: LoadOptions) -> Result<Document> {
+ Self::load_internal(source, None, options)
+ }
+
+ /// Load a PDF document from an arbitrary source with a password for encrypted PDFs.
+ #[deprecated(since = "0.41.0", note = "Use load_from_with_options instead")]
+ #[inline]
+ pub fn load_from_with_password<R: Read>(source: R, password: &str) -> Result<Document> {
+ Self::load_from_with_options(source, LoadOptions::with_password(password))
+ }
+
+ fn load_internal<R: Read>(mut source: R, capacity: Option<usize>, options: LoadOptions) -> Result<Document> {
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer)?;
+
+ Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: options.password,
+ strict: options.strict,
+ max_decompressed_size: options.max_decompressed_size,
+ normal_offsets: Vec::new(),
+ }
+ .read(options.filter)
+ }
+
+ /// Load a PDF document from a memory slice.
+ pub fn load_mem(buffer: &[u8]) -> Result<Document> {
+ Self::load_mem_with_options(buffer, LoadOptions::default())
+ }
+
+ /// Load a PDF document from a memory slice with the given options.
+ pub fn load_mem_with_options(buffer: &[u8], options: LoadOptions) -> Result<Document> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: options.password,
+ strict: options.strict,
+ max_decompressed_size: options.max_decompressed_size,
+ normal_offsets: Vec::new(),
+ }
+ .read(options.filter)
+ }
+
+ /// Load a PDF document from a memory slice with a password for encrypted PDFs.
+ #[deprecated(since = "0.41.0", note = "Use load_mem_with_options instead")]
+ pub fn load_mem_with_password(buffer: &[u8], password: &str) -> Result<Document> {
+ Self::load_mem_with_options(buffer, LoadOptions::with_password(password))
+ }
+
+ /// Load PDF metadata (title and page count) without loading the entire document.
+ /// This is much faster for large PDFs when you only need basic information.
+ #[inline]
+ pub fn load_metadata<P: AsRef<Path>>(path: P) -> Result<PdfMetadata> {
+ let file = File::open(path)?;
+ let capacity = Some(file.metadata()?.len() as usize);
+ Self::load_metadata_internal(file, capacity, None)
+ }
+
+ /// Load PDF metadata from a file path with a password for encrypted PDFs.
+ #[inline]
+ pub fn load_metadata_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<PdfMetadata> {
+ let file = File::open(path)?;
+ let capacity = Some(file.metadata()?.len() as usize);
+ Self::load_metadata_internal(file, capacity, Some(password.to_string()))
+ }
+
+ /// Load PDF metadata from an arbitrary source without loading the entire document.
+ #[inline]
+ pub fn load_metadata_from<R: Read>(source: R) -> Result<PdfMetadata> {
+ Self::load_metadata_internal(source, None, None)
+ }
+
+ /// Load PDF metadata from an arbitrary source with a password for encrypted PDFs.
+ #[inline]
+ pub fn load_metadata_from_with_password<R: Read>(source: R, password: &str) -> Result<PdfMetadata> {
+ Self::load_metadata_internal(source, None, Some(password.to_string()))
+ }
+
+ /// Load PDF metadata from a memory slice without loading the entire document.
+ #[inline]
+ pub fn load_metadata_mem(buffer: &[u8]) -> Result<PdfMetadata> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+
+ /// Load PDF metadata from a memory slice with a password for encrypted PDFs.
+ #[inline]
+ pub fn load_metadata_mem_with_password(buffer: &[u8], password: &str) -> Result<PdfMetadata> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: Some(password.to_string()),
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+
+ fn load_metadata_internal<R: Read>(
+ mut source: R, capacity: Option<usize>, password: Option<String>,
+ ) -> Result<PdfMetadata> {
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer)?;
+
+ Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+}
+
+#[cfg(feature = "async")]
+impl Document {
+ pub async fn load<P: AsRef<Path>>(path: P) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::default()).await
+ }
+
+ /// Load a PDF document from a specified file path with the given options.
+ pub async fn load_with_options<P: AsRef<Path>>(path: P, options: LoadOptions) -> Result<Document> {
+ let file = File::open(path).await?;
+ let metadata = file.metadata().await?;
+ let capacity = Some(metadata.len() as usize);
+ Self::load_internal(file, capacity, options).await
+ }
+
+ /// Load a PDF document from a specified file path with a password for encrypted PDFs.
+ pub async fn load_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::with_password(password)).await
+ }
+
+ #[deprecated(since = "0.41.0", note = "Use load_with_options instead")]
+ pub async fn load_filtered<P: AsRef<Path>>(path: P, filter_func: FilterFunc) -> Result<Document> {
+ Self::load_with_options(path, LoadOptions::with_filter(filter_func)).await
+ }
+
+ async fn load_internal<R: AsyncRead>(source: R, capacity: Option<usize>, options: LoadOptions) -> Result<Document> {
+ pin!(source);
+
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer).await?;
+
+ Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: options.password,
+ strict: options.strict,
+ max_decompressed_size: options.max_decompressed_size,
+ normal_offsets: Vec::new(),
+ }
+ .read(options.filter)
+ }
+
+ /// Load a PDF document from a memory slice.
+ pub fn load_mem(buffer: &[u8]) -> Result<Document> {
+ Self::load_mem_with_options(buffer, LoadOptions::default())
+ }
+
+ /// Load a PDF document from a memory slice with the given options.
+ pub fn load_mem_with_options(buffer: &[u8], options: LoadOptions) -> Result<Document> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: options.password,
+ strict: options.strict,
+ max_decompressed_size: options.max_decompressed_size,
+ normal_offsets: Vec::new(),
+ }
+ .read(options.filter)
+ }
+
+ /// Load PDF metadata (title and page count) without loading the entire document.
+ /// This is much faster for large PDFs when you only need basic information.
+ #[inline]
+ pub async fn load_metadata<P: AsRef<Path>>(path: P) -> Result<PdfMetadata> {
+ let file = File::open(path).await?;
+ let metadata = file.metadata().await?;
+ let capacity = Some(metadata.len() as usize);
+ Self::load_metadata_internal(file, capacity, None).await
+ }
+
+ /// Load PDF metadata from a file path with a password for encrypted PDFs.
+ #[inline]
+ pub async fn load_metadata_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<PdfMetadata> {
+ let file = File::open(path).await?;
+ let metadata = file.metadata().await?;
+ let capacity = Some(metadata.len() as usize);
+ Self::load_metadata_internal(file, capacity, Some(password.to_string())).await
+ }
+
+ /// Load PDF metadata from an arbitrary source without loading the entire document.
+ #[inline]
+ pub async fn load_metadata_from<R: AsyncRead>(source: R) -> Result<PdfMetadata> {
+ Self::load_metadata_internal(source, None, None).await
+ }
+
+ /// Load PDF metadata from an arbitrary source with a password for encrypted PDFs.
+ #[inline]
+ pub async fn load_metadata_from_with_password<R: AsyncRead>(source: R, password: &str) -> Result<PdfMetadata> {
+ Self::load_metadata_internal(source, None, Some(password.to_string())).await
+ }
+
+ /// Load PDF metadata from a memory slice without loading the entire document.
+ #[inline]
+ pub fn load_metadata_mem(buffer: &[u8]) -> Result<PdfMetadata> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+
+ /// Load PDF metadata from a memory slice with a password for encrypted PDFs.
+ #[inline]
+ pub fn load_metadata_mem_with_password(buffer: &[u8], password: &str) -> Result<PdfMetadata> {
+ Reader {
+ buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: Some(password.to_string()),
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+
+ async fn load_metadata_internal<R: AsyncRead>(
+ source: R, capacity: Option<usize>, password: Option<String>,
+ ) -> Result<PdfMetadata> {
+ pin!(source);
+
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer).await?;
+
+ Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read_metadata()
+ }
+}
+
+impl TryInto<Document> for &[u8] {
+ type Error = Error;
+
+ fn try_into(self) -> Result<Document> {
+ Reader {
+ buffer: self,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read(None)
+ }
+}
+
+#[cfg(not(feature = "async"))]
+impl IncrementalDocument {
+ /// Load a PDF document from a specified file path.
+ #[inline]
+ pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
+ let file = File::open(path)?;
+ let capacity = Some(file.metadata()?.len() as usize);
+ Self::load_internal(file, capacity)
+ }
+
+ /// Load a PDF document from an arbitrary source.
+ #[inline]
+ pub fn load_from<R: Read>(source: R) -> Result<Self> {
+ Self::load_internal(source, None)
+ }
+
+ fn load_internal<R: Read>(mut source: R, capacity: Option<usize>) -> Result<Self> {
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer)?;
+
+ let document = Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read(None)?;
+
+ Ok(IncrementalDocument::create_from(buffer, document))
+ }
+
+ /// Load a PDF document from a memory slice.
+ pub fn load_mem(buffer: &[u8]) -> Result<Document> {
+ buffer.try_into()
+ }
+}
+
+#[cfg(feature = "async")]
+impl IncrementalDocument {
+ /// Load a PDF document from a specified file path.
+ #[inline]
+ pub async fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
+ let file = File::open(path).await?;
+ let metadata = file.metadata().await?;
+ let capacity = Some(metadata.len() as usize);
+ Self::load_internal(file, capacity).await
+ }
+
+ /// Load a PDF document from an arbitrary source.
+ #[inline]
+ pub async fn load_from<R: AsyncRead>(source: R) -> Result<Self> {
+ Self::load_internal(source, None).await
+ }
+
+ async fn load_internal<R: AsyncRead>(source: R, capacity: Option<usize>) -> Result<Self> {
+ pin!(source);
+
+ let mut buffer = capacity.map(Vec::with_capacity).unwrap_or_default();
+ source.read_to_end(&mut buffer).await?;
+
+ let document = Reader {
+ buffer: &buffer,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read(None)?;
+
+ Ok(IncrementalDocument::create_from(buffer, document))
+ }
+
+ /// Load a PDF document from a memory slice.
+ pub fn load_mem(buffer: &[u8]) -> Result<Document> {
+ buffer.try_into()
+ }
+}
+
+impl TryInto<IncrementalDocument> for &[u8] {
+ type Error = Error;
+
+ fn try_into(self) -> Result<IncrementalDocument> {
+ let document = Reader {
+ buffer: self,
+ document: Document::new(),
+ encryption_state: None,
+ raw_objects: BTreeMap::new(),
+ password: None,
+ strict: false,
+ max_decompressed_size: None,
+ normal_offsets: Vec::new(),
+ }
+ .read(None)?;
+
+ Ok(IncrementalDocument::create_from(self.to_vec(), document))
+ }
+}
+
+pub struct Reader<'a> {
+ pub buffer: &'a [u8],
+ pub document: Document,
+ pub encryption_state: Option<EncryptionState>,
+ pub raw_objects: BTreeMap<ObjectId, Vec<u8>>, // Store raw bytes for encrypted objects
+ pub password: Option<String>, // Password for encrypted PDFs
+ pub strict: bool, // Reject non-conforming PDFs when true
+ /// Maximum decompressed size, in bytes, allowed for any single stream
+ /// (object streams and cross-reference streams) decoded during loading.
+ /// `None` (the default) applies no limit; set it to guard against
+ /// decompression bombs. See [`crate::LoadOptions`].
+ pub max_decompressed_size: Option<usize>,
+ /// Sorted unique byte offsets of every `XrefEntry::Normal` entry in the
+ /// final cross-reference table. Built once when the table is complete so
+ /// object-boundary lookups can binary-search the successor offset instead
+ /// of scanning all xref entries on each call.
+ normal_offsets: Vec<usize>,
+}
+
+/// Maximum allowed embedding of literal strings.
+pub const MAX_BRACKET: usize = 100;
+
+pub const MAX_NESTING_DEPTH: usize = 100;
+
+/// Cap on reconstructed cross-reference entries, bounding memory on hostile inputs.
+const MAX_RECONSTRUCTED_OBJECTS: usize = 1_000_000;
+
+/// Cap on how many trailing `trailer` dictionaries are inspected for a `/Root`.
+const MAX_TRAILER_CANDIDATES: usize = 16;
+
+/// PDF metadata extracted without loading the entire document.
+/// This is useful for quickly getting basic information about large PDFs.
+#[derive(Debug, Clone)]
+pub struct PdfMetadata {
+ /// Document title from Info dictionary
+ pub title: Option<String>,
+ /// Document author from Info dictionary
+ pub author: Option<String>,
+ /// Document subject from Info dictionary
+ pub subject: Option<String>,
+ /// Document keywords from Info dictionary
+ pub keywords: Option<String>,
+ /// Application that created the document
+ pub creator: Option<String>,
+ /// Application that produced the document
+ pub producer: Option<String>,
+ /// Document creation date (PDF date format: D:YYYYMMDDHHmmSSOHH'mm')
+ pub creation_date: Option<String>,
+ /// Document modification date (PDF date format: D:YYYYMMDDHHmmSSOHH'mm')
+ pub modification_date: Option<String>,
+ /// Custom Info dictionary entries that are not part of the standard set above.
+ ///
+ /// Producers commonly use the Info dictionary to attach application-specific
+ /// metadata (for example, Microsoft Information Protection labels stored as
+ /// `MSIP_Label_{GUID}_{Property}` keys). Such entries used to be discarded
+ /// by the metadata-only loader; they are now preserved here as raw `Object`
+ /// values so callers can inspect or decode them as needed.
+ pub custom: HashMap<Vec<u8>, Object>,
+ /// Number of pages in the document
+ pub page_count: u32,
+ /// PDF version
+ pub version: String,
+ /// Whether the document declares encryption (an `/Encrypt` entry in the
+ /// trailer). When `true`, string and stream contents are encrypted; the
+ /// standard Info fields above are populated only if the document could be
+ /// decrypted — e.g. an empty user password, or a password supplied via a
+ /// `*_with_password` loader.
+ pub encrypted: bool,
+}
+
+struct InfoMetadata {
+ title: Option<String>,
+ author: Option<String>,
+ subject: Option<String>,
+ keywords: Option<String>,
+ creator: Option<String>,
+ producer: Option<String>,
+ creation_date: Option<String>,
+ modification_date: Option<String>,
+ custom: HashMap<Vec<u8>, Object>,
+}
+
+impl InfoMetadata {
+ fn empty() -> Self {
+ Self {
+ title: None,
+ author: None,
+ subject: None,
+ keywords: None,
+ creator: None,
+ producer: None,
+ creation_date: None,
+ modification_date: None,
+ custom: HashMap::new(),
+ }
+ }
+}
+
+/// Standard Info dictionary keys defined in PDF 1.7 §14.3.3 ("Document
+/// Information Dictionary"). Any other key is preserved on
+/// `PdfMetadata::custom` rather than dropped.
+const STANDARD_INFO_KEYS: &[&[u8]] = &[
+ b"Title",
+ b"Author",
+ b"Subject",
+ b"Keywords",
+ b"Creator",
+ b"Producer",
+ b"CreationDate",
+ b"ModDate",
+ b"Trapped",
+];
+
+impl Reader<'_> {
+ /// Read metadata (title and page count) without loading the entire document.
+ /// This is much faster for large PDFs when you only need basic information.
+ ///
+ /// For encrypted PDFs, use `Document::load_metadata_with_password()` instead.
+ pub fn read_metadata(mut self) -> Result<PdfMetadata> {
+ let offset = self.buffer.windows(5).position(|w| w == b"%PDF-").unwrap_or(0);
+ self.buffer = &self.buffer[offset..];
+
+ let version = parser::header(self.buffer, self.strict).ok_or(ParseError::InvalidFileHeader)?;
+
+ let (xref, trailer) = match self.resolve_xref_and_trailer() {
+ Ok(resolved) => resolved,
+ Err(err) => match self.reconstruct_xref_and_trailer() {
+ Some(reconstructed) => {
+ warn!("cross-reference resolution failed ({err}); recovered by scanning for indirect objects");
+ reconstructed
+ }
+ None => return Err(err),
+ },
+ };
+
+ self.set_reference_table(xref);
+ self.document.trailer = trailer.clone();
+ let encrypted = self.document.trailer.get(b"Encrypt").is_ok();
+ // For encrypted PDFs, set up decryption so the Info dictionary can be
+ // read. If the document is protected by a password we cannot supply,
+ // still report what we have (notably `encrypted`) rather than failing
+ // the whole call; callers needing the Info fields should use a
+ // `*_with_password` loader.
+ let needs_password = if encrypted {
+ match self.setup_encryption_for_metadata() {
+ Ok(()) => false,
+ // No usable password was available (empty password failed and
+ // none was supplied): report `encrypted` without the Info
+ // fields. A wrong supplied password still surfaces as an error.
+ Err(Error::Unimplemented(_)) => true,
+ Err(e) => return Err(e),
+ }
+ } else {
+ false
+ };
+
+ let info_metadata = if needs_password {
+ InfoMetadata::empty()
+ } else {
+ self.extract_info_metadata()?
+ };
+ let page_count = if needs_password { 0 } else { self.extract_page_count()? };
+
+ Ok(PdfMetadata {
+ title: info_metadata.title,
+ author: info_metadata.author,
+ subject: info_metadata.subject,
+ keywords: info_metadata.keywords,
+ creator: info_metadata.creator,
+ producer: info_metadata.producer,
+ creation_date: info_metadata.creation_date,
+ modification_date: info_metadata.modification_date,
+ custom: info_metadata.custom,
+ page_count,
+ version,
+ encrypted,
+ })
+ }
+
+ fn extract_info_metadata(&self) -> Result<InfoMetadata> {
+ let info_ref = match self.document.trailer.get(b"Info") {
+ Ok(obj) => obj.as_reference().ok(),
+ Err(_) => return Ok(InfoMetadata::empty()),
+ };
+
+ let info_id = match info_ref {
+ Some(id) => id,
+ None => return Ok(InfoMetadata::empty()),
+ };
+
+ let mut already_seen = HashSet::new();
+ let info_obj = match self.get_object(info_id, &mut already_seen) {
+ Ok(obj) => obj,
+ Err(_) => return Ok(InfoMetadata::empty()),
+ };
+
+ let info_dict = match info_obj.as_dict() {
+ Ok(dict) => dict,
+ Err(_) => return Ok(InfoMetadata::empty()),
+ };
+
+ let mut custom = HashMap::new();
+ for (key, value) in info_dict.iter() {
+ if STANDARD_INFO_KEYS.contains(&key.as_slice()) {
+ continue;
+ }
+ custom.insert(key.clone(), value.clone());
+ }
+
+ Ok(InfoMetadata {
+ title: Self::extract_string_field(info_dict, b"Title"),
+ author: Self::extract_string_field(info_dict, b"Author"),
+ subject: Self::extract_string_field(info_dict, b"Subject"),
+ keywords: Self::extract_string_field(info_dict, b"Keywords"),
+ creator: Self::extract_string_field(info_dict, b"Creator"),
+ producer: Self::extract_string_field(info_dict, b"Producer"),
+ creation_date: Self::extract_string_field(info_dict, b"CreationDate"),
+ modification_date: Self::extract_string_field(info_dict, b"ModDate"),
+ custom,
+ })
+ }
+
+ fn extract_string_field(dict: &Dictionary, key: &[u8]) -> Option<String> {
+ match dict.get(key) {
+ Ok(obj) => match obj {
+ Object::String(_bytes, _) => common_data_structures::decode_text_string(obj).ok(),
+ _ => None,
+ },
+ Err(_) => None,
+ }
+ }
+
+ fn extract_page_count(&self) -> Result<u32> {
+ let root_ref = match self.document.trailer.get(b"Root").and_then(Object::as_reference) {
+ Ok(id) => id,
+ Err(_) => return Ok(0),
+ };
+
+ let mut already_seen = HashSet::new();
+ let catalog_obj = match self.get_object(root_ref, &mut already_seen) {
+ Ok(obj) => obj,
+ Err(_) => return Ok(0),
+ };
+
+ let catalog_dict = match catalog_obj.as_dict() {
+ Ok(dict) => dict,
+ Err(_) => return Ok(0),
+ };
+
+ let pages_ref = match catalog_dict.get(b"Pages").and_then(Object::as_reference) {
+ Ok(id) => id,
+ Err(_) => return Ok(0),
+ };
+
+ self.get_pages_tree_count(pages_ref, &mut HashSet::new(), 0).or(Ok(0))
+ }
+
+ fn get_pages_tree_count(&self, pages_id: ObjectId, seen: &mut HashSet<ObjectId>, depth: usize) -> Result<u32> {
+ // `seen` catches a repeated node (a cycle); it does not bound the depth of a long,
+ // non-cyclic /Pages chain with no /Count, which recurses once per level. Cap that
+ // separately, matching this crate's existing MAX_NESTING_DEPTH budget.
+ if depth >= MAX_NESTING_DEPTH {
+ return Ok(0);
+ }
+ if seen.contains(&pages_id) {
+ return Err(Error::ReferenceCycle(pages_id));
+ }
+ seen.insert(pages_id);
+
+ let mut already_seen = HashSet::new();
+ let pages_obj = match self.get_object(pages_id, &mut already_seen) {
+ Ok(obj) => obj,
+ Err(_) => return Ok(0),
+ };
+
+ let pages_dict = match pages_obj.as_dict() {
+ Ok(dict) => dict,
+ Err(_) => return Ok(0),
+ };
+
+ match pages_dict.get_type() {
+ Ok(type_name) if type_name == b"Page" => Ok(1),
+ Ok(type_name) if type_name == b"Pages" => {
+ if let Ok(count_obj) = pages_dict.get(b"Count")
+ && let Ok(count) = count_obj.as_i64()
+ && count >= 0
+ {
+ return Ok(count as u32);
+ }
+
+ let kids = match pages_dict.get(b"Kids").and_then(Object::as_array) {
+ Ok(arr) => arr,
+ Err(_) => return Ok(0),
+ };
+
+ let mut total = 0u32;
+ for kid in kids.iter() {
+ if let Ok(kid_ref) = kid.as_reference()
+ && let Ok(count) = self.get_pages_tree_count(kid_ref, seen, depth + 1)
+ {
+ total += count;
+ }
+ }
+ Ok(total)
+ }
+ _ => Ok(1),
+ }
+ }
+
+ /// Read whole document.
+ pub fn read(mut self, filter_func: Option<FilterFunc>) -> Result<Document> {
+ let offset = self.buffer.windows(5).position(|w| w == b"%PDF-").unwrap_or(0);
+ self.buffer = &self.buffer[offset..];
+
+ // The document structure can be expressed in PEG as:
+ // document <- header indirect_object* xref trailer xref_start
+ let version = parser::header(self.buffer, self.strict).ok_or(ParseError::InvalidFileHeader)?;
+
+ //The binary_mark is in line 2 after the pdf version. If at other line number, then will be declared as invalid
+ // pdf.
+ if let Some(pos) = self.buffer.iter().position(|&byte| byte == b'\n')
+ && let Some(binary_mark) = parser::binary_mark(&self.buffer[pos + 1..])
+ && binary_mark.iter().all(|&byte| byte >= 128)
+ {
+ self.document.binary_mark = binary_mark;
+ }
+
+ // Fall back to reconstruction only after all standard resolution fails.
+ let (xref, trailer) = match self.resolve_xref_and_trailer() {
+ Ok(resolved) => resolved,
+ Err(err) => match self.reconstruct_xref_and_trailer() {
+ Some(reconstructed) => {
+ warn!("cross-reference resolution failed ({err}); recovered by scanning for indirect objects");
+ reconstructed
+ }
+ None => return Err(err),
+ },
+ };
+
+ self.document.version = version;
+ self.document.max_id = xref.size - 1;
+ self.document.trailer = trailer;
+ self.set_reference_table(xref);
+
+ // Check if encrypted
+ let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok();
+
+ if is_encrypted {
+ // For encrypted PDFs, use a special loading strategy
+ self.load_encrypted_document(filter_func)?;
+ } else {
+ // For non-encrypted PDFs, use the normal loading
+ self.load_objects_raw(filter_func)?;
+ }
+
+ // Object-stream members join `objects` only during loading, after
+ // `max_id` was derived from the xref size. Keep the ceiling at least
+ // at the highest loaded object so new ids cannot collide with live ones.
+ if let Some(&max_loaded_id) = self.document.objects.keys().next_back() {
+ self.document.max_id = self.document.max_id.max(max_loaded_id.0);
+ }
+
+ Ok(self.document)
+ }
+
+ fn load_encrypted_document(&mut self, _filter_func: Option<FilterFunc>) -> Result<()> {
+ // First, extract all raw object bytes without parsing
+ let entries: Vec<_> = self
+ .document
+ .reference_table
+ .entries
+ .iter()
+ .map(|(k, v)| (*k, v.clone()))
+ .collect();
+
+ let mut object_streams = Vec::new();
+
+ for (obj_num, entry) in entries {
+ match entry {
+ XrefEntry::Normal { offset, .. } => {
+ if let Ok((obj_id, raw_bytes)) = self.extract_raw_object(offset as usize) {
+ self.raw_objects.insert(obj_id, raw_bytes);
+ }
+ }
+ XrefEntry::Compressed { container, index } => {
+ // Store compressed object info for later processing
+ object_streams.push((obj_num, container, index));
+ }
+ XrefEntry::Free | XrefEntry::UnusableFree => {
+ // Skip free entries
+ }
+ }
+ }
+
+ self.parse_encryption_dictionary()?;
+
+ if self.authenticate_and_setup_encryption(false)?.is_none() {
+ return Ok(());
+ }
+
+ if let Some(ref state) = self.encryption_state {
+ let encrypt_ref = self
+ .document
+ .trailer
+ .get(b"Encrypt")
+ .ok()
+ .and_then(|o| o.as_reference().ok());
+
+ for (obj_id, raw_bytes) in &self.raw_objects {
+ if let Some(enc_ref) = encrypt_ref
+ && *obj_id == enc_ref
+ {
+ continue;
+ }
+
+ if let Ok((id, mut obj)) = self.parse_raw_object(raw_bytes) {
+ let _ = encryption::decrypt_object(state, *obj_id, &mut obj);
+ self.document.objects.insert(id, obj);
+ }
+ }
+
+ let mut streams_to_process: std::collections::HashMap<u32, Vec<(u32, u16)>> =
+ std::collections::HashMap::new();
+ for (obj_num, container_id, index) in object_streams {
+ streams_to_process
+ .entry(container_id)
+ .or_default()
+ .push((obj_num, index));
+ }
+
+ for (container_id, objects_in_stream) in streams_to_process {
+ if let Some(container_obj) = self.document.objects.get(&(container_id, 0))
+ && let Ok(stream) = container_obj.as_stream()
+ {
+ match ObjectStream::new_with_limit(stream, self.max_decompressed_size) {
+ Ok(object_stream) => {
+ for (obj_num, _index) in objects_in_stream {
+ let obj_id = (obj_num, 0);
+ if let Some(obj) = object_stream.objects.get(&obj_id) {
+ self.document.objects.insert(obj_id, obj.clone());
+ }
+ }
+ }
+ Err(_e) => {}
+ }
+ }
+ }
+
+ let mut stored_state = state.clone();
+ // Record the /Encrypt dictionary's object id so that a later
+ // incremental save can restore `/Encrypt N G R` in the appended
+ // trailer. See `IncrementalDocument::save_internal`.
+ stored_state.encrypt_object_id = encrypt_ref;
+ self.document.encryption_state = Some(stored_state);
+
+ if let Some(enc_ref) = encrypt_ref {
+ self.document.objects.remove(&enc_ref);
+ }
+ self.document.trailer.remove(b"Encrypt");
+ }
+
+ Ok(())
+ }
+
+ fn parse_raw_object(&self, raw_bytes: &[u8]) -> Result<(ObjectId, Object)> {
+ // Parse the raw bytes as an indirect object
+ parser::indirect_object(raw_bytes, 0, None, self, &mut HashSet::new(), None)
+ }
+
+ /// Install a fully merged cross-reference table and derive its sorted
+ /// offset index. All later object-boundary lookups go through that index,
+ /// so it must be rebuilt whenever the table is replaced.
+ fn set_reference_table(&mut self, xref: Xref) {
+ let mut normal_offsets: Vec<usize> = xref
+ .entries
+ .values()
+ .filter_map(|entry| match entry {
+ XrefEntry::Normal { offset, .. } => Some(*offset as usize),
+ _ => None,
+ })
+ .collect();
+ normal_offsets.sort_unstable();
+ normal_offsets.dedup();
+ self.normal_offsets = normal_offsets;
+ self.document.reference_table = xref;
+ }
+
+ fn load_objects_raw(&mut self, filter_func: Option<FilterFunc>) -> Result<()> {
+ let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok();
+ let zero_length_streams = Mutex::new(vec![]);
+ let object_streams = Mutex::new(vec![]);
+
+ // Build a map of which container each compressed object belongs to
+ // according to the xref. This prevents stale ObjStm copies (e.g., from
+ // linearization first-page sections) from overriding the correct version.
+ let compressed_obj_containers: BTreeMap<u32, u32> = self
+ .document
+ .reference_table
+ .entries
+ .iter()
+ .filter_map(|(&id, entry)| {
+ if let XrefEntry::Compressed { container, .. } = entry {
+ Some((id, *container))
+ } else {
+ None
+ }
+ })
+ .collect();
+ let normal_offsets = &self.normal_offsets;
+
+ let entries_filter_map = |(_, entry): (&_, &_)| -> Result<Option<(ObjectId, Object)>> {
+ if let XrefEntry::Normal { offset, .. } = *entry {
+ // read_object now handles decryption internally
+ let offset = offset as usize;
+ let next_index = normal_offsets.partition_point(|&next| next <= offset);
+ let next_object = normal_offsets.get(next_index).copied();
+ let end = self.object_end(offset, next_object);
+ let result = self.read_object_to(offset, end, None, &mut HashSet::new());
+ let (object_id, mut object) = match result {
+ Ok(obj) => obj,
+ Err(e) => {
+ if is_encrypted {
+ // Expected for some encrypted objects - but log which
+ // ones. These failures stay non-fatal even in strict
+ // mode because they do not indicate a malformed file.
+ warn!("Skipping encrypted object at offset {}: {:?}", offset, e);
+ return Ok(None);
+ }
+ // Lenient loading logs and skips malformed objects; strict loading fails.
+ error!("Object load error at offset {}: {e:?}", offset);
+ return if self.strict { Err(e) } else { Ok(None) };
+ }
+ };
+ if let Some(filter_func) = filter_func
+ && filter_func(object_id, &mut object).is_none()
+ {
+ return Ok(None);
+ }
+
+ if let Ok(stream) = object.as_stream() {
+ if stream.dict.has_type(b"ObjStm") && !is_encrypted {
+ let obj_stream = match ObjectStream::new_with_limit(stream, self.max_decompressed_size) {
+ Ok(obj_stream) => obj_stream,
+ // Not an encryption-related loss, so it obeys the same
+ // strict-mode policy as any other load error.
+ Err(e) => {
+ error!("Object stream load error for {object_id:?}: {e:?}");
+ return if self.strict { Err(e) } else { Ok(None) };
+ }
+ };
+ let container_id = object_id.0;
+ let mut object_streams = object_streams.lock().unwrap();
+ if let Some(filter_func) = filter_func {
+ let objects: BTreeMap<(u32, u16), Object> = obj_stream
+ .objects
+ .into_iter()
+ .filter(|((obj_num, _), _)| {
+ compressed_obj_containers
+ .get(obj_num)
+ .is_none_or(|&c| c == container_id)
+ })
+ .filter_map(|(object_id, mut object)| filter_func(object_id, &mut object))
+ .collect();
+ object_streams.extend(objects);
+ } else {
+ object_streams.extend(obj_stream.objects.into_iter().filter(|((obj_num, _), _)| {
+ compressed_obj_containers
+ .get(obj_num)
+ .is_none_or(|&c| c == container_id)
+ }));
+ }
+ } else if stream.content.is_empty() {
+ let mut zero_length_streams = zero_length_streams.lock().unwrap();
+ zero_length_streams.push(object_id);
+ }
+ }
+
+ Ok(Some((object_id, object)))
+ } else {
+ Ok(None)
+ }
+ };
+
+ #[cfg(feature = "rayon")]
+ {
+ self.document.objects = self
+ .document
+ .reference_table
+ .entries
+ .par_iter()
+ .map(entries_filter_map)
+ .filter_map(Result::transpose)
+ .collect::<Result<BTreeMap<_, _>>>()?;
+ }
+ #[cfg(not(feature = "rayon"))]
+ {
+ self.document.objects = self
+ .document
+ .reference_table
+ .entries
+ .iter()
+ .map(entries_filter_map)
+ .filter_map(Result::transpose)
+ .collect::<Result<BTreeMap<_, _>>>()?;
+ }
+
+ // Only add entries, but never replace entries
+ for (id, entry) in object_streams.into_inner().unwrap() {
+ self.document.objects.entry(id).or_insert(entry);
+ }
+
+ for object_id in zero_length_streams.into_inner().unwrap() {
+ let _ = self.read_stream_content(object_id);
+ }
+
+ Ok(())
+ }
+
+ fn read_stream_content(&mut self, object_id: ObjectId) -> Result<()> {
+ let length = self.get_stream_length(object_id)?;
+ let stream = self
+ .document
+ .get_object_mut(object_id)
+ .and_then(Object::as_stream_mut)?;
+ let start = stream
+ .start_position
+ .ok_or(Error::InvalidStream("missing start position".to_string()))?;
+
+ if length < 0 {
+ return Err(Error::InvalidStream("negative stream length.".to_string()));
+ }
+
+ let length = usize::try_from(length).map_err(|e| Error::NumericCast(e.to_string()))?;
+ let end = start + length;
+
+ if end > self.buffer.len() {
+ return Err(Error::InvalidStream("stream extends after document end.".to_string()));
+ }
+
+ stream.set_content(self.buffer[start..end].to_vec());
+ Ok(())
+ }
+
+ fn get_stream_length(&self, object_id: ObjectId) -> Result<i64> {
+ let object = self.document.get_object(object_id)?;
+ let stream = object.as_stream()?;
+ stream
+ .dict
+ .get(b"Length")
+ .and_then(|value| self.document.dereference(value))
+ .and_then(|(_id, obj)| match obj.as_i64() {
+ Ok(length) => Ok(length),
+ // ISO 32000-1 s7.3.8.2 requires /Length to be an integer, but some producers
+ // write it as a real ("42." instead of "42"). Accept one whose value is
+ // integral and in range rather than dropping the stream's content.
+ Err(err) => match obj.as_f32() {
+ Ok(value) if value.fract() == 0.0 && value >= -(2f32.powi(63)) && value < 2f32.powi(63) => {
+ Ok(value as i64)
+ }
+ _ => Err(err),
+ },
+ })
+ .inspect_err(|_err| {
+ error!(
+ "stream dictionary of '{} {} R' is missing the Length entry",
+ object_id.0, object_id.1
+ );
+ })
+ }
+
+ /// Get object offset by object ID.
+ fn get_offset(&self, id: ObjectId) -> Result<u32> {
+ let entry = self.document.reference_table.get(id.0).ok_or(Error::MissingXrefEntry)?;
+ match *entry {
+ XrefEntry::Normal { offset, generation } if generation == id.1 => Ok(offset),
+ _ => Err(Error::MissingXrefEntry),
+ }
+ }
+
+ /// Load a compressed object from an object stream (for lightweight metadata extraction)
+ fn get_compressed_object(&self, id: ObjectId) -> Result<Object> {
+ let entry = self.document.reference_table.get(id.0).ok_or(Error::MissingXrefEntry)?;
+
+ let container_id = match entry {
+ XrefEntry::Compressed { container, .. } => *container,
+ _ => return Err(Error::MissingXrefEntry),
+ };
+
+ let container_id = (container_id, 0);
+ let mut already_seen = HashSet::new();
+ let container_obj = self.get_object(container_id, &mut already_seen)?;
+ let container_stream = container_obj.as_stream()?;
+ let object_stream = ObjectStream::new_with_limit(container_stream, self.max_decompressed_size)?;
+ object_stream.objects.get(&id).cloned().ok_or(Error::MissingXrefEntry)
+ }
+
+ pub fn get_object(&self, id: ObjectId, already_seen: &mut HashSet<ObjectId>) -> Result<Object> {
+ if already_seen.contains(&id) {
+ warn!("reference cycle detected resolving object {} {}", id.0, id.1);
+ return Err(Error::ReferenceCycle(id));
+ }
+ already_seen.insert(id);
+
+ if let Some(entry) = self.document.reference_table.get(id.0)
+ && matches!(entry, XrefEntry::Compressed { .. })
+ {
+ return self.get_compressed_object(id);
+ }
+
+ let offset = self.get_offset(id)?;
+ let (_, mut obj) = self.read_object(offset as usize, Some(id), already_seen)?;
+
+ if let Some(ref state) = self.encryption_state {
+ let encrypt_ref = self
+ .document
+ .trailer
+ .get(b"Encrypt")
+ .ok()
+ .and_then(|o| o.as_reference().ok());
+ if let Some(enc_ref) = encrypt_ref
+ && id != enc_ref
+ {
+ encryption::decrypt_object(state, id, &mut obj).map_err(Error::Decryption)?;
+ }
+ }
+
+ Ok(obj)
+ }
+
+ fn parse_encryption_dictionary(&mut self) -> Result<()> {
+ if let Ok(encrypt_ref) = self.document.trailer.get(b"Encrypt").and_then(|o| o.as_reference()) {
+ if self.raw_objects.is_empty() {
+ let offset = self.get_offset(encrypt_ref)?;
+ let (_, encrypt_obj) = self.read_object(offset as usize, Some(encrypt_ref), &mut HashSet::new())?;
+ self.document.objects.insert(encrypt_ref, encrypt_obj);
+ } else if let Some(raw_bytes) = self.raw_objects.get(&encrypt_ref)
+ && let Ok((_, obj)) = self.parse_raw_object(raw_bytes)
+ {
+ self.document.objects.insert(encrypt_ref, obj);
+ }
+ }
+ Ok(())
+ }
+
+ fn authenticate_and_setup_encryption(&mut self, require_password: bool) -> Result<Option<String>> {
+ let password_to_use: Option<String> = if self.document.authenticate_password("").is_ok() {
+ Some(String::new())
+ } else if let Some(ref pwd) = self.password {
+ if self.document.authenticate_password(pwd).is_ok() {
+ Some(pwd.clone())
+ } else if require_password {
+ return Err(Error::InvalidPassword);
+ } else {
+ warn!("Invalid password provided for encrypted PDF");
+ return Err(Error::InvalidPassword);
+ }
+ } else if require_password {
+ return Err(Error::Unimplemented(
+ "PDF is encrypted and requires a password. Use Document::load_metadata_with_password() instead.",
+ ));
+ } else {
+ warn!("PDF is encrypted and requires a password");
+ return Ok(None);
+ };
+
+ if let Some(ref password) = password_to_use {
+ let state = EncryptionState::decode(&self.document, password)?;
+ self.encryption_state = Some(state);
+ }
+
+ Ok(password_to_use)
+ }
+
+ fn setup_encryption_for_metadata(&mut self) -> Result<()> {
+ self.parse_encryption_dictionary()?;
+ self.authenticate_and_setup_encryption(true)?;
+ Ok(())
+ }
+
+ fn extract_raw_object(&mut self, offset: usize) -> Result<(ObjectId, Vec<u8>)> {
+ if offset > self.buffer.len() {
+ return Err(Error::InvalidOffset(offset));
+ }
+
+ // Find object header (e.g., "19 0 obj")
+ let slice = &self.buffer[offset..];
+
+ // Parse object ID
+ let mut pos = 0;
+ while pos < slice.len() && slice[pos].is_ascii_whitespace() {
+ pos += 1;
+ }
+
+ // Get object number
+ let num_start = pos;
+ while pos < slice.len() && slice[pos].is_ascii_digit() {
+ pos += 1;
+ }
+ let obj_num: u32 = std::str::from_utf8(&slice[num_start..pos])
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .ok_or(Error::Parse(ParseError::InvalidXref))?;
+
+ // Skip whitespace
+ while pos < slice.len() && slice[pos].is_ascii_whitespace() {
+ pos += 1;
+ }
+
+ // Get generation number
+ let gen_start = pos;
+ while pos < slice.len() && slice[pos].is_ascii_digit() {
+ pos += 1;
+ }
+ let obj_gen: u16 = std::str::from_utf8(&slice[gen_start..pos])
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .ok_or(Error::Parse(ParseError::InvalidXref))?;
+
+ // Skip to "obj"
+ while pos < slice.len() && slice[pos].is_ascii_whitespace() {
+ pos += 1;
+ }
+ if pos + 3 > slice.len() || &slice[pos..pos + 3] != b"obj" {
+ return Err(Error::Parse(ParseError::InvalidXref));
+ }
+ pos += 3;
+
+ // Find "endobj"
+ let endobj_pattern = b"endobj";
+ let mut end_pos = pos;
+ while end_pos + endobj_pattern.len() <= slice.len() {
+ if &slice[end_pos..end_pos + endobj_pattern.len()] == endobj_pattern {
+ end_pos += endobj_pattern.len();
+ break;
+ }
+ end_pos += 1;
+ }
+
+ if end_pos > slice.len() {
+ return Err(Error::Parse(ParseError::InvalidXref));
+ }
+
+ // Extract raw object bytes (including header and trailer)
+ let raw_bytes = slice[0..end_pos].to_vec();
+
+ Ok(((obj_num, obj_gen), raw_bytes))
+ }
+
+ fn read_object(
+ &self, offset: usize, expected_id: Option<ObjectId>, already_seen: &mut HashSet<ObjectId>,
+ ) -> Result<(ObjectId, Object)> {
+ let next_index = self.normal_offsets.partition_point(|&next| next <= offset);
+ let end = self.object_end(offset, self.normal_offsets.get(next_index).copied());
+ self.read_object_to(offset, end, expected_id, already_seen)
+ }
+
+ fn object_end(&self, offset: usize, next_object: Option<usize>) -> usize {
+ let xref_start = (self.document.xref_start > offset).then_some(self.document.xref_start);
+ next_object
+ .into_iter()
+ .chain(xref_start)
+ .min()
+ .unwrap_or(self.buffer.len())
+ .min(self.buffer.len())
+ }
+
+ fn read_object_to(
+ &self, offset: usize, end: usize, expected_id: Option<ObjectId>, already_seen: &mut HashSet<ObjectId>,
+ ) -> Result<(ObjectId, Object)> {
+ if offset > end || end > self.buffer.len() {
+ return Err(Error::InvalidOffset(offset));
+ }
+
+ // Objects are parsed against the full buffer so a wrong *neighbor*
+ // xref offset cannot truncate a well-formed object; `end` only limits
+ // how far malformed-stream length recovery may scan.
+ parser::indirect_object(self.buffer, offset, expected_id, self, already_seen, Some(end))
+ }
+
+ /// Parse the cross-reference section recorded at `offset`, first correcting
+ /// the offset if it is slightly miswritten (lenient mode only).
+ fn xref_and_trailer_at(&self, offset: usize) -> Result<(Xref, Dictionary)> {
+ let offset = self.correct_xref_offset(offset);
+ parser::xref_and_trailer(&self.buffer[offset..], self)
+ }
+
+ /// Resolve the cross-reference table/stream and trailer, including the
+ /// `/Prev` chain, and record the resolved start offset on the document.
+ fn resolve_xref_and_trailer(&mut self) -> Result<(Xref, Dictionary)> {
+ let xref_start = Self::get_xref_start(self.buffer)?;
+ if xref_start > self.buffer.len() {
+ return Err(Error::Xref(XrefError::Start));
+ }
+ let xref_start = self.correct_xref_offset(xref_start);
+ self.document.xref_start = xref_start;
+
+ let (mut xref, mut trailer) = self.xref_and_trailer_at(xref_start)?;
+
+ // Read previous Xrefs of linearized or incremental updated document.
+ let mut already_seen = HashSet::new();
+ let mut prev_xref_start = trailer.remove(b"Prev");
+ while let Some(prev) = prev_xref_start.and_then(|offset| offset.as_i64().ok()) {
+ if already_seen.contains(&prev) {
+ break;
+ }
+ already_seen.insert(prev);
+ if prev < 0 || prev as usize > self.buffer.len() {
+ return Err(Error::Xref(XrefError::PrevStart));
+ }
+
+ let (prev_xref, prev_trailer) = self.xref_and_trailer_at(prev as usize)?;
+ xref.merge(prev_xref);
+
+ // Read xref stream in hybrid-reference file
+ let prev_xref_stream_start = trailer.remove(b"XRefStm");
+ if let Some(prev) = prev_xref_stream_start.and_then(|offset| offset.as_i64().ok()) {
+ if prev < 0 || prev as usize > self.buffer.len() {
+ return Err(Error::Xref(XrefError::StreamStart));
+ }
+
+ let (prev_xref, _) = self.xref_and_trailer_at(prev as usize)?;
+ xref.merge(prev_xref);
+ }
+
+ prev_xref_start = prev_trailer.get(b"Prev").cloned().ok();
+ }
+ let xref_entry_count = xref.max_id().checked_add(1).ok_or(ParseError::InvalidXref)?;
+ if xref.size != xref_entry_count {
+ warn!(
+ "Size entry of trailer dictionary is {}, correct value is {}.",
+ xref.size, xref_entry_count
+ );
+ xref.size = xref_entry_count;
+ }
+
+ Ok((xref, trailer))
+ }
+
+ /// Last-resort recovery: rebuild the cross-reference table by scanning the
+ /// raw bytes for indirect-object headers and locating a trailer with a
+ /// usable `/Root`. Returns `None` (caller keeps the original error) when
+ /// strict mode forbids recovery or nothing usable was found.
+ fn reconstruct_xref_and_trailer(&mut self) -> Option<(Xref, Dictionary)> {
+ if self.strict {
+ return None;
+ }
+ u32::try_from(self.buffer.len()).ok()?;
+
+ let markers = Self::scan_object_markers(self.buffer);
+ if markers.is_empty() {
+ return None;
+ }
+
+ let mut xref = Xref::new(markers.len() as u32, XrefType::CrossReferenceTable);
+ for (offset, (number, generation)) in markers {
+ // Incremental updates append, so later revisions win.
+ xref.insert(number, XrefEntry::Normal { offset, generation });
+ }
+ // Normalize like `resolve_xref_and_trailer`: size spans object numbers
+ // up to the highest, not physical copies across incremental updates.
+ xref.size = xref.max_id().saturating_add(1);
+
+ let (_trailer_pos, trailer) = self.find_latest_trailer(&xref)?;
+ // deliberate: no on-disk table exists to point at. Zero marks the
+ // offset "unknown" so `Document::new_from_prev` omits `/Prev` instead
+ // of recording end-of-file; `object_end` clamps to the buffer either way.
+ self.document.xref_start = 0;
+
+ warn!(
+ "reconstructed cross-reference table with {} objects by scanning for indirect objects",
+ xref.entries.len()
+ );
+ Some((xref, trailer))
+ }
+
+ /// Collect `(offset, id)` of every indirect-object header in one pass.
+ /// Only headers starting a line (optional leading blanks allowed) count,
+ /// stream payloads are skipped wholesale, and object numbers beyond
+ /// [`MAX_RECONSTRUCTED_OBJECTS`] are rejected so a forged header can
+ /// neither shadow a genuine entry nor poison the reconstructed size.
+ fn scan_object_markers(buffer: &[u8]) -> Vec<(u32, ObjectId)> {
+ const STREAM_KEYWORD: &[u8] = b"stream";
+ const END_STREAM_KEYWORD: &[u8] = b"endstream";
+
+ let mut markers = Vec::new();
+ let mut oversized_number_warned = false;
+ let mut at_line_start = true;
+ let mut pos = 0;
+ while pos < buffer.len() {
+ // Skip raw stream data: an uncompressed payload may embed
+ // convincing `N G obj` lines whose later offsets would otherwise
+ // override the genuine entries for those object numbers.
+ if buffer[pos..].starts_with(STREAM_KEYWORD)
+ && !buffer[..pos].ends_with(b"end")
+ && matches!(buffer.get(pos + STREAM_KEYWORD.len()), Some(b'\r' | b'\n'))
+ {
+ let after_keyword = pos + STREAM_KEYWORD.len();
+ if let Some(relative) = buffer[after_keyword..]
+ .windows(END_STREAM_KEYWORD.len())
+ .position(|window| window == END_STREAM_KEYWORD)
+ {
+ pos = after_keyword + relative + END_STREAM_KEYWORD.len();
+ at_line_start = false;
+ continue;
+ }
+ // Damaged stream without terminator: fall back to the
+ // dictionary's /Length hint so the payload cannot hide
+ // line-start pseudo headers, while objects written after it
+ // stay reachable.
+ if let Some(resume) = Self::payload_end_by_length(buffer, pos) {
+ pos = resume;
+ at_line_start = false;
+ continue;
+ }
+ // Unusable /Length too: nothing bounds the payload, so keep
+ // scanning byte by byte rather than dropping what follows.
+ }
+ // Anchor at line starts so pseudo headers buried after another
+ // token (string literal, comment) are never mistaken for markers.
+ if at_line_start
+ && buffer[pos].is_ascii_digit()
+ && let Some(id) = Self::parse_object_header(&buffer[pos..])
+ {
+ // A huge bogus number would inflate `size` (and thus
+ // `max_id`) via `Xref::insert`; genuine numbering stays
+ // within the same cap as the marker count.
+ if id.0 > MAX_RECONSTRUCTED_OBJECTS as u32 {
+ if !oversized_number_warned {
+ warn!("ignoring object headers numbered above {MAX_RECONSTRUCTED_OBJECTS}");
+ oversized_number_warned = true;
+ }
+ } else {
+ if markers.len() == MAX_RECONSTRUCTED_OBJECTS {
+ warn!(
+ "object marker scan stopped at the {MAX_RECONSTRUCTED_OBJECTS}-marker cap; reconstruction may be incomplete"
+ );
+ break;
+ }
+ markers.push((pos as u32, id));
+ }
+ }
+ match buffer[pos] {
+ b'\r' | b'\n' => at_line_start = true,
+ b' ' | b'\t' => {}
+ _ => at_line_start = false,
+ }
+ pos += 1;
+ }
+ markers
+ }
+
+ /// Resume offset past a stream payload according to a *direct* `/Length`
+ /// integer in the dictionary preceding the `stream` keyword at
+ /// `stream_pos`. The search is scoped to the current object (after the
+ /// nearest preceding `obj` keyword) so a missing `/Length` cannot latch
+ /// onto a previous object's value. Returns `None` when the hint is
+ /// absent, indirect, or points outside the buffer — damaged files tend
+ /// to carry wrong `/Length` values, so it must stay a hint, never a hard
+ /// boundary.
+ fn payload_end_by_length(buffer: &[u8], stream_pos: usize) -> Option<usize> {
+ const LENGTH_KEY: &[u8] = b"/Length";
+ const OBJ_KEYWORD: &[u8] = b"obj";
+ const STREAM_KEYWORD_LEN: usize = b"stream".len();
+
+ let head = &buffer[..stream_pos];
+ let obj_pos = head
+ .windows(OBJ_KEYWORD.len())
+ .rposition(|window| window == OBJ_KEYWORD)?;
+ let dict_region = &buffer[obj_pos + OBJ_KEYWORD.len()..stream_pos];
+ // Nearest `/Length` in this object's dictionary; parsing it validates
+ // that the match really is a key with an integer value.
+ let key_pos = dict_region
+ .windows(LENGTH_KEY.len())
+ .rposition(|window| window == LENGTH_KEY)?;
+ let rest = &dict_region[key_pos + LENGTH_KEY.len()..];
+ let digits_start = rest.iter().position(u8::is_ascii_digit)?;
+ let digits_len = rest[digits_start..]
+ .iter()
+ .take_while(|byte| byte.is_ascii_digit())
+ .count();
+ if digits_len > 10 {
+ return None;
+ }
+ // An indirect reference (`/Length 5 0 R`) continues with another
+ // number token; a direct integer ends at a name, `>>`, or the keyword.
+ match rest[digits_start + digits_len..]
+ .iter()
+ .copied()
+ .find(|byte| !byte.is_ascii_whitespace())
+ {
+ Some(b'/') | Some(b'>') => {}
+ _ => return None,
+ }
+ let length: usize = std::str::from_utf8(&rest[digits_start..digits_start + digits_len])
+ .ok()?
+ .parse()
+ .ok()?;
+ // Spec: the EOL after the `stream` keyword counts as CRLF or LF.
+ let eol_len = match (
+ buffer.get(stream_pos + STREAM_KEYWORD_LEN),
+ buffer.get(stream_pos + STREAM_KEYWORD_LEN + 1),
+ ) {
+ (Some(b'\r'), Some(b'\n')) => 2,
+ _ => 1,
+ };
+ let end = (stream_pos + STREAM_KEYWORD_LEN + eol_len).checked_add(length)?;
+ (buffer.len() >= end).then_some(end)
+ }
+
+ /// Parse an `N G obj` header; the byte after `obj` must end the token.
+ fn parse_object_header(input: &[u8]) -> Option<ObjectId> {
+ // deliberate: caps at u32/u16 width bound work on pathological padding.
+ fn digits(input: &[u8], cap: usize) -> Option<(&[u8], &[u8])> {
+ let n = input.iter().take_while(|b| b.is_ascii_digit()).count();
+ (0 < n && n <= cap).then(|| input.split_at(n))
+ }
+ fn spaces(input: &[u8]) -> Option<&[u8]> {
+ let n = input
+ .iter()
+ .take_while(|&&b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'))
+ .count();
+ (n > 0).then(|| &input[n..])
+ }
+
+ let (number, rest) = digits(input, 10)?;
+ let number: u32 = std::str::from_utf8(number).ok()?.parse().ok()?;
+ let rest = spaces(rest)?;
+ let (generation, rest) = digits(rest, 5)?;
+ let generation: u16 = std::str::from_utf8(generation).ok()?.parse().ok()?;
+ let rest = spaces(rest)?;
+ let tail = rest.strip_prefix(b"obj")?;
+ match tail.first() {
+ None => {}
+ Some(&byte) if !byte.is_ascii_alphanumeric() => {}
+ _ => return None,
+ }
+ Some((number, generation))
+ }
+
+ /// Newest backwards-scanned `trailer` whose `/Root` references a scanned object.
+ fn find_latest_trailer(&self, xref: &Xref) -> Option<(usize, Dictionary)> {
+ let mut bound = self.buffer.len();
+ for _ in 0..MAX_TRAILER_CANDIDATES {
+ let Some(pos) = Reader::search_substring(&self.buffer[..bound], b"trailer", 0) else {
+ break;
+ };
+ bound = pos;
+
+ let after_keyword = &self.buffer[pos + b"trailer".len()..];
+ let Some(dict_start) = after_keyword.iter().position(|byte| !byte.is_ascii_whitespace()) else {
+ continue;
+ };
+ let Ok((_, dict)) = parser::dictionary(&after_keyword[dict_start..]) else {
+ continue;
+ };
+ if dict
+ .get(b"Root")
+ .and_then(Object::as_reference)
+ .is_ok_and(|root| xref.entries.contains_key(&root.0))
+ {
+ return Some((pos, dict));
+ }
+ }
+ None
+ }
+
+ /// Some generators write `startxref` (or trailer `Prev`) values that are
+ /// slightly off — most commonly the offset of the line *after* the `xref`
+ /// keyword instead of the keyword itself. Such files are otherwise intact,
+ /// and common readers (Acrobat, poppler, mupdf, pdf.js) recover from them.
+ /// In lenient mode, if `offset` does not point at a cross-reference table
+ /// or an indirect object (cross-reference stream), scan a small window
+ /// around it for the `xref` keyword and use the nearest match instead.
+ fn correct_xref_offset(&self, offset: usize) -> usize {
+ const RECOVERY_WINDOW: usize = 64;
+
+ if self.strict || offset >= self.buffer.len() {
+ return offset;
+ }
+ let rest = &self.buffer[offset..];
+ if rest.starts_with(b"xref") || Self::starts_indirect_object(rest) {
+ return offset;
+ }
+
+ let window_start = offset.saturating_sub(RECOVERY_WINDOW);
+ let window_end = cmp::min(self.buffer.len(), offset + RECOVERY_WINDOW);
+ let mut corrected: Option<usize> = None;
+ for pos in window_start..window_end.saturating_sub(4) {
+ if !self.buffer[pos..].starts_with(b"xref") {
+ continue;
+ }
+ // `startxref` contains `xref`; never match inside it.
+ if pos >= 5 && &self.buffer[pos - 5..pos] == b"start" {
+ continue;
+ }
+ if corrected.is_none_or(|best: usize| pos.abs_diff(offset) < best.abs_diff(offset)) {
+ corrected = Some(pos);
+ }
+ }
+ match corrected {
+ Some(pos) => {
+ warn!(
+ "Cross-reference offset {} does not point at an xref section; using nearby offset {} instead.",
+ offset, pos
+ );
+ pos
+ }
+ None => offset,
+ }
+ }
+
+ /// Whether `input` begins with an indirect-object header (`N G obj`), the
+ /// form a cross-reference stream starts with.
+ fn starts_indirect_object(input: &[u8]) -> bool {
+ Self::parse_object_header(input).is_some()
+ }
+
+ fn get_xref_start(buffer: &[u8]) -> Result<usize> {
+ let seek_pos = buffer.len() - cmp::min(buffer.len(), 512);
+ Self::search_substring(buffer, b"%%EOF", seek_pos)
+ .filter(|&eof_pos| eof_pos > 25)
+ .and_then(|eof_pos| Self::search_substring(&buffer[..eof_pos], b"startxref", eof_pos - 25))
+ .ok_or(Error::Xref(XrefError::Start))
+ .and_then(|xref_pos| {
+ if xref_pos <= buffer.len() {
+ match parser::xref_start(&buffer[xref_pos..]) {
+ Some(startxref) => Ok(startxref as usize),
+ None => Err(Error::Xref(XrefError::Start)),
+ }
+ } else {
+ Err(Error::Xref(XrefError::Start))
+ }
+ })
+ }
+
+ fn search_substring(buffer: &[u8], pattern: &[u8], start_pos: usize) -> Option<usize> {
+ buffer
+ .get(start_pos..)?
+ .windows(pattern.len())
+ .rposition(|window| window == pattern)
+ .map(|pos| start_pos + pos)
+ }
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn load_document() {
+ let mut doc = Document::load("assets/example.pdf").unwrap();
+ assert_eq!(doc.version, "1.5");
+
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir().unwrap();
+ let file_path = temp_dir.path().join("test_2_load.pdf");
+ doc.save(file_path).unwrap();
+}
+
+#[cfg(all(test, feature = "async"))]
+#[tokio::test]
+async fn load_document() {
+ let mut doc = Document::load("assets/example.pdf").await.unwrap();
+ assert_eq!(doc.version, "1.5");
+
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir().unwrap();
+ let file_path = temp_dir.path().join("test_2_load.pdf");
+ doc.save(file_path).unwrap();
+}
+
+#[test]
+#[should_panic(expected = "Xref(Start)")]
+fn load_short_document() {
+ let _doc = Document::load_mem(b"%PDF-1.5\n%%EOF\n").unwrap();
+}
+
+#[test]
+fn load_document_with_preceding_bytes() {
+ let mut content = Vec::new();
+ content.extend(b"garbage");
+ content.extend(include_bytes!("../assets/example.pdf"));
+ let doc = Document::load_mem(&content).unwrap();
+ assert_eq!(doc.version, "1.5");
+}
+
+#[test]
+fn load_many_shallow_brackets() {
+ let content: String = std::iter::repeat_n("()", MAX_BRACKET * 10)
+ .flat_map(|x| x.chars())
+ .collect();
+ const STREAM_CRUFT: usize = 33;
+ let doc = format!(
+ "%PDF-1.5
+1 0 obj<</Type/Pages/Kids[5 0 R]/Count 1/Resources 3 0 R/MediaBox[0 0 595 842]>>endobj
+2 0 obj<</Type/Font/Subtype/Type1/BaseFont/Courier>>endobj
+3 0 obj<</Font<</F1 2 0 R>>>>endobj
+5 0 obj<</Type/Page/Parent 1 0 R/Contents[4 0 R]>>endobj
+6 0 obj<</Type/Catalog/Pages 1 0 R>>endobj
+4 0 obj<</Length {}>>stream
+BT
+/F1 48 Tf
+100 600 Td
+({}) Tj
+ET
+endstream endobj\n",
+ content.len() + STREAM_CRUFT,
+ content
+ );
+ let doc = format!(
+ "{}xref
+0 7
+0000000000 65535 f
+0000000009 00000 n
+0000000096 00000 n
+0000000155 00000 n
+0000000291 00000 n
+0000000191 00000 n
+0000000248 00000 n
+trailer
+<</Root 6 0 R/Size 7>>
+startxref
+{}
+%%EOF",
+ doc,
+ doc.len()
+ );
+
+ let _doc = Document::load_mem(doc.as_bytes()).unwrap();
+}
+
+#[test]
+fn load_too_deep_brackets() {
+ let content: Vec<u8> = std::iter::repeat_n(b'(', MAX_BRACKET + 1)
+ .chain(std::iter::repeat_n(b')', MAX_BRACKET + 1))
+ .collect();
+ let content = String::from_utf8(content).unwrap();
+ const STREAM_CRUFT: usize = 33;
+ let doc = format!(
+ "%PDF-1.5
+1 0 obj<</Type/Pages/Kids[5 0 R]/Count 1/Resources 3 0 R/MediaBox[0 0 595 842]>>endobj
+2 0 obj<</Type/Font/Subtype/Type1/BaseFont/Courier>>endobj
+3 0 obj<</Font<</F1 2 0 R>>>>endobj
+5 0 obj<</Type/Page/Parent 1 0 R/Contents[7 0 R 4 0 R]>>endobj
+6 0 obj<</Type/Catalog/Pages 1 0 R>>endobj
+7 0 obj<</Length 45>>stream
+BT /F1 48 Tf 100 600 Td (Hello World!) Tj ET
+endstream
+endobj
+4 0 obj<</Length {}>>stream
+BT
+/F1 48 Tf
+100 600 Td
+({}) Tj
+ET
+endstream endobj\n",
+ content.len() + STREAM_CRUFT,
+ content
+ );
+ let doc = format!(
+ "{}xref
+0 7
+0000000000 65535 f
+0000000009 00000 n
+0000000096 00000 n
+0000000155 00000 n
+0000000387 00000 n
+0000000191 00000 n
+0000000254 00000 n
+0000000297 00000 n
+trailer
+<</Root 6 0 R/Size 7>>
+startxref
+{}
+%%EOF",
+ doc,
+ doc.len()
+ );
+
+ let doc = Document::load_mem(doc.as_bytes()).unwrap();
+ let pages = doc.get_pages().keys().cloned().collect::<Vec<_>>();
+ assert_eq!("Hello World!\n", doc.extract_text(&pages).unwrap());
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn search_substring_finds_last_occurrence() {
+ assert_eq!(Reader::search_substring(b"hello world", b"xyz", 0), None);
+ assert_eq!(Reader::search_substring(b"hello world", b"world", 0), Some(6));
+
+ let buffer = b"%%EOF\ntest%%EOF\nend";
+ assert_eq!(Reader::search_substring(buffer, b"%%EOF", 0), Some(10));
+ assert_eq!(Reader::search_substring(buffer, b"%%EOF", 6), Some(10));
+ assert_eq!(Reader::search_substring(buffer, b"%%EOF", 15), None);
+ assert_eq!(Reader::search_substring(b"%%EOF", b"%%EOF", 0), Some(0));
+
+ let buffer_with_many_percents = b"%%%PDF-1.3%%%comment%%%more%%EOF";
+ assert_eq!(
+ Reader::search_substring(buffer_with_many_percents, b"%%EOF", 0),
+ Some(27)
+ );
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn get_xref_start_ignores_startxref_past_eof() {
+ // Simulate a PDF with two revisions where the second has a corrupted %%EOF.
+ // The valid %%EOF is at a known position; a second startxref appears after it
+ // but belongs to the corrupted revision. get_xref_start must pick the
+ // startxref *before* the valid %%EOF.
+ let mut buf = Vec::new();
+ // Padding so the buffer is large enough
+ buf.extend_from_slice(&[b' '; 200]);
+ // First (correct) startxref + xref offset + valid %%EOF
+ let xref_offset = 100usize;
+ let startxref_block = format!("startxref\n{}\n%%EOF\n", xref_offset);
+ let _startxref_pos = buf.len();
+ buf.extend_from_slice(startxref_block.as_bytes());
+ // Second (corrupted) revision: another startxref pointing elsewhere, with %%EO\0
+ let bad_block = "startxref\n999\n%%EO\x00\n".to_string();
+ buf.extend_from_slice(bad_block.as_bytes());
+
+ let result = Reader::get_xref_start(&buf).unwrap();
+ // Should find the xref_offset from the first startxref (before valid %%EOF)
+ assert_eq!(result, xref_offset);
+ // Verify it did NOT pick up 999 from the corrupted revision
+ assert_ne!(result, 999);
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn recovers_from_miswritten_startxref_offset() {
+ // Some generators write the offset of the line *after* the `xref` keyword
+ // into `startxref` instead of the offset of the keyword itself. Lenient
+ // loading must recover; strict loading must still reject the file.
+ let header = "%PDF-1.5\n";
+ let obj1 = "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n";
+ let obj2 = "2 0 obj<</Type/Pages/Kids[]/Count 0>>endobj\n";
+ let o1 = header.len();
+ let o2 = o1 + obj1.len();
+ let body = format!("{header}{obj1}{obj2}");
+ let xref_pos = body.len();
+ let doc = format!(
+ "{body}xref
+0 3
+0000000000 65535 f
+{o1:010} 00000 n
+{o2:010} 00000 n
+trailer
+<</Root 1 0 R/Size 3>>
+startxref
+{}
+%%EOF",
+ xref_pos + 4 // past the `xref` keyword, onto the line after it
+ );
+
+ let loaded = Document::load_mem(doc.as_bytes()).unwrap();
+ assert!(loaded.trailer.get(b"Root").is_ok());
+ assert_eq!(loaded.xref_start, xref_pos);
+
+ let strict = Document::load_mem_with_options(
+ doc.as_bytes(),
+ LoadOptions {
+ strict: true,
+ ..Default::default()
+ },
+ );
+ assert!(strict.is_err());
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn stream_length_written_as_real() {
+ // ISO 32000-1 s7.3.8.2 requires /Length to be an integer, but some generators
+ // emit "/Length 42." instead of "/Length 42". Such a stream must still resolve
+ // to its content rather than silently loading as empty.
+ let obj4 = "4 0 obj\n<< /Length 42. >>\nstream\nBT /F1 12 Tf 20 100 Td (Hello World) Tj ET\nendstream\nendobj\n";
+ let header = "%PDF-1.7\n";
+ let obj1 = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
+ let obj2 = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
+ let obj3 = "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>\nendobj\n";
+ let o1 = header.len();
+ let o2 = o1 + obj1.len();
+ let o3 = o2 + obj2.len();
+ let o4 = o3 + obj3.len();
+ let body = format!("{header}{obj1}{obj2}{obj3}{obj4}");
+ let xref_pos = body.len();
+ let doc = format!(
+ "{body}xref
+0 5
+0000000000 65535 f
+{o1:010} 00000 n
+{o2:010} 00000 n
+{o3:010} 00000 n
+{o4:010} 00000 n
+trailer
+<< /Size 5 /Root 1 0 R >>
+startxref
+{xref_pos}
+%%EOF
+"
+ );
+
+ let loaded = Document::load_mem(doc.as_bytes()).unwrap();
+ let stream = loaded.get_object((4, 0)).unwrap().as_stream().unwrap();
+ assert_eq!(stream.content, b"BT /F1 12 Tf 20 100 Td (Hello World) Tj ET");
+}
+
+#[cfg(all(test, not(feature = "async")))]
+#[test]
+fn object_marker_parsing_accepts_only_real_headers() {
+ assert_eq!(Reader::parse_object_header(b"12 0 obj<<"), Some((12, 0)));
+ assert_eq!(Reader::parse_object_header(b"007 0 obj\n"), Some((7, 0)));
+ assert_eq!(Reader::parse_object_header(b"5 2 obj>>"), Some((5, 2)));
+ assert_eq!(Reader::parse_object_header(b"12\t3\r\nobj["), Some((12, 3)));
+ assert_eq!(Reader::parse_object_header(b"2 0 objects"), None);
+ assert_eq!(Reader::parse_object_header(b"99 88 objx"), None);
+ assert_eq!(Reader::parse_object_header(b"12345678901 0 obj"), None);
+ assert_eq!(Reader::parse_object_header(b"1 70000 obj"), None);
+ assert_eq!(Reader::parse_object_header(b"1 0obj"), None);
+ assert_eq!(Reader::parse_object_header(b"1 obj"), None);
+ assert_eq!(Reader::parse_object_header(b"x 0 obj"), None);
+}
diff --git a/vendor/lopdf/src/save_options.rs b/vendor/lopdf/src/save_options.rs
new file mode 100644
index 000000000..e6744e1b7
--- /dev/null
+++ b/vendor/lopdf/src/save_options.rs
@@ -0,0 +1,83 @@
+use crate::ObjectStreamConfig;
+
+/// Options for saving PDF documents
+#[derive(Debug, Clone, Default)]
+pub struct SaveOptions {
+ /// Enable object streams for compressing non-stream objects
+ pub use_object_streams: bool,
+
+ /// Enable cross-reference streams instead of traditional xref tables
+ pub use_xref_streams: bool,
+
+ /// Enable linearization (fast web view)
+ pub linearize: bool,
+
+ /// Configuration for object streams
+ pub object_stream_config: ObjectStreamConfig,
+}
+
+impl SaveOptions {
+ /// Create a builder for SaveOptions
+ pub fn builder() -> SaveOptionsBuilder {
+ SaveOptionsBuilder::default()
+ }
+}
+
+/// Builder for SaveOptions
+#[derive(Default)]
+pub struct SaveOptionsBuilder {
+ use_object_streams: bool,
+ use_xref_streams: bool,
+ linearize: bool,
+ max_objects_per_stream: usize,
+ compression_level: u32,
+}
+
+impl SaveOptionsBuilder {
+ /// Enable or disable object streams
+ pub fn use_object_streams(mut self, value: bool) -> Self {
+ self.use_object_streams = value;
+ self
+ }
+
+ /// Enable or disable cross-reference streams
+ pub fn use_xref_streams(mut self, value: bool) -> Self {
+ self.use_xref_streams = value;
+ self
+ }
+
+ /// Enable or disable linearization
+ pub fn linearize(mut self, value: bool) -> Self {
+ self.linearize = value;
+ self
+ }
+
+ /// Set maximum objects per stream
+ pub fn max_objects_per_stream(mut self, value: usize) -> Self {
+ self.max_objects_per_stream = value;
+ self
+ }
+
+ /// Set compression level (0-9)
+ pub fn compression_level(mut self, value: u32) -> Self {
+ self.compression_level = value;
+ self
+ }
+
+ /// Build the SaveOptions
+ pub fn build(self) -> SaveOptions {
+ SaveOptions {
+ use_object_streams: self.use_object_streams,
+ use_xref_streams: self.use_xref_streams,
+ linearize: self.linearize,
+ object_stream_config: ObjectStreamConfig {
+ max_objects_per_stream: if self.max_objects_per_stream == 0 {
+ 100
+ } else {
+ self.max_objects_per_stream
+ },
+ compression_level: self.compression_level,
+ },
+ }
+ }
+}
diff --git a/vendor/lopdf/src/toc.rs b/vendor/lopdf/src/toc.rs
new file mode 100644
index 000000000..68f9b7390
--- /dev/null
+++ b/vendor/lopdf/src/toc.rs
@@ -0,0 +1,222 @@
+use indexmap::IndexMap;
+
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Serialize};
+
+use super::{Document, Error, Object, ObjectId, Outline, Result};
+
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TocType {
+ pub level: usize,
+ pub title: String,
+ pub page: usize,
+}
+
+#[allow(dead_code)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[derive(Debug, Clone, Default)]
+pub struct Toc {
+ pub toc: Vec<TocType>,
+ pub errors: Vec<String>,
+}
+
+impl Toc {
+ pub fn new() -> Self {
+ Toc {
+ toc: Vec::new(),
+ errors: Vec::new(),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Destination {
+ map: IndexMap<Vec<u8>, Object>,
+}
+
+#[allow(dead_code)]
+impl Destination {
+ pub fn new(title: Object, page: Object, typ: Object) -> Self {
+ let mut map = IndexMap::new();
+ map.insert(b"Title".to_vec(), title);
+ map.insert(b"Page".to_vec(), page);
+ map.insert(b"Type".to_vec(), typ);
+ Destination { map }
+ }
+
+ pub fn set(&mut self, key: Vec<u8>, value: Object) {
+ self.map.insert(key, value);
+ }
+
+ pub fn title(&self) -> Option<&Object> {
+ self.map.get(b"Title".as_slice())
+ }
+
+ pub fn page(&self) -> Option<&Object> {
+ self.map.get(b"Page".as_slice())
+ }
+}
+
+type OutlinePageIds = Vec<(Vec<u8>, ObjectId, usize)>;
+
+fn setup_outline_page_ids<'a>(
+ outlines: &'a Vec<Outline>, result: &mut OutlinePageIds, level: usize,
+) -> Result<&'a Vec<Outline>> {
+ for outline in outlines.iter() {
+ match outline {
+ Outline::Destination(destination) => {
+ result.push((
+ destination.title()?.as_str()?.to_vec(),
+ destination.page()?.as_reference()?,
+ level,
+ ));
+ }
+ Outline::SubOutlines(sub_outlines) => {
+ setup_outline_page_ids(sub_outlines, result, level + 1)?;
+ }
+ }
+ }
+ Ok(outlines)
+}
+
+impl Document {
+ fn setup_page_id_to_num(&self) -> IndexMap<(u32, u16), u32> {
+ let mut result = IndexMap::new();
+ for (page_num, page_id) in self.get_pages() {
+ result.insert(page_id, page_num);
+ }
+ result
+ }
+
+ pub fn get_toc(&self) -> Result<Toc> {
+ let mut toc: Toc = Toc {
+ toc: Vec::new(),
+ errors: Vec::new(),
+ };
+ let mut named_destinations = IndexMap::new();
+
+ let Some(outlines) = self.get_outlines(None, None, &mut named_destinations)? else {
+ return Err(Error::NoOutline);
+ };
+
+ let mut outline_page_ids = Vec::new();
+ setup_outline_page_ids(&outlines, &mut outline_page_ids, 1)?;
+ let page_id_to_page_numbers = self.setup_page_id_to_num();
+ for (title, page_id, level) in outline_page_ids {
+ if let Some(page_num) = page_id_to_page_numbers.get(&page_id) {
+ let s = if title.len() < 2 {
+ String::from_utf8_lossy(&title).to_string()
+ } else if title[0] == 0xfe && title[1] == 0xff {
+ if title.len() & 1 != 0 {
+ toc.errors
+ .push(format!("Title encoded UTF16_BE {title:?} has invalid length!"));
+ continue;
+ }
+ let t16: Vec<u16> = title
+ .chunks(2)
+ .skip(1)
+ .map(|x| ((x[0] as u16) << 8) | x[1] as u16)
+ .collect();
+ String::from_utf16_lossy(&t16)
+ } else if title[0] == 0xff && title[1] == 0xfe {
+ if title.len() & 1 != 0 {
+ toc.errors
+ .push(format!("Title encoded UTF16_LE {title:?} has invalid length!"));
+ continue;
+ }
+ let t16: Vec<u16> = title
+ .chunks(2)
+ .skip(1)
+ .map(|x| ((x[1] as u16) << 8) | x[0] as u16)
+ .collect();
+ String::from_utf16_lossy(&t16)
+ } else {
+ String::from_utf8_lossy(&title).to_string()
+ };
+ toc.toc.push(TocType {
+ level,
+ title: s,
+ page: *page_num as usize,
+ });
+ }
+ }
+ Ok(toc)
+ }
+}
+
+#[cfg(not(feature = "async"))]
+#[cfg(test)]
+mod tests {
+ use crate::{Document, TocType};
+
+ #[test]
+ fn parse_toc() {
+ let expected = vec![
+ TocType {
+ level: 1,
+ title: String::from("1. Flesh Fruits"),
+ page: 1,
+ },
+ TocType {
+ level: 2,
+ title: String::from("1.1. Stone Fruits"),
+ page: 2,
+ },
+ TocType {
+ level: 3,
+ title: String::from("1.1.1. Peaches"),
+ page: 3,
+ },
+ TocType {
+ level: 3,
+ title: String::from("1.1.2. Plums"),
+ page: 6,
+ },
+ TocType {
+ level: 2,
+ title: String::from("1.2. Pomes"),
+ page: 28,
+ },
+ TocType {
+ level: 3,
+ title: String::from("1.2.1. Apples"),
+ page: 30,
+ },
+ TocType {
+ level: 3,
+ title: String::from("1.2.2. Pears"),
+ page: 35,
+ },
+ TocType {
+ level: 2,
+ title: String::from("Summary"),
+ page: 36,
+ },
+ TocType {
+ level: 1,
+ title: String::from("2. Berries & Hesperidia"),
+ page: 40,
+ },
+ TocType {
+ level: 2,
+ title: String::from("2.1. True Berries"),
+ page: 40,
+ },
+ TocType {
+ level: 2,
+ title: String::from("Summary"),
+ page: 41,
+ },
+ TocType {
+ level: 1,
+ title: String::from("3. The End"),
+ page: 100,
+ },
+ ];
+
+ let doc = Document::load("assets/test.pdf").unwrap();
+ let toc = doc.get_toc().unwrap();
+ assert_eq!(toc.toc, expected);
+ }
+}
diff --git a/vendor/lopdf/src/writer.rs b/vendor/lopdf/src/writer.rs
new file mode 100644
index 000000000..05bdc845b
--- /dev/null
+++ b/vendor/lopdf/src/writer.rs
@@ -0,0 +1,834 @@
+use std::fs::File;
+use std::io::{BufWriter, Result, Write};
+use std::path::Path;
+use std::vec;
+
+use super::Object::*;
+use super::{Dictionary, Document, Object, Stream, StringFormat};
+use crate::encryption;
+use crate::{IncrementalDocument, xref::*};
+
+impl Document {
+ /// Save PDF document to specified file path.
+ #[inline]
+ pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<File> {
+ let mut file = BufWriter::new(File::create(path)?);
+ self.save_internal(&mut file)?;
+ Ok(file.into_inner()?)
+ }
+
+ /// Save PDF to arbitrary target
+ #[inline]
+ pub fn save_to<W: Write>(&mut self, target: &mut W) -> Result<()> {
+ self.save_internal(target)
+ }
+
+ /// Save PDF with custom options
+ ///
+ /// Object streams are skipped for an encrypted document, which is written with every
+ /// object serialized individually instead. See [`Document::save_modern`].
+ pub fn save_with_options<W: Write>(&mut self, target: &mut W, options: crate::SaveOptions) -> Result<()> {
+ // Cross-reference streams are independent of object streams: a document can use one
+ // without the other. Select the requested type here so the choice applies whichever
+ // path writes the body below. Both features arrived in PDF 1.5, so a document that is
+ // about to use one is moved up to that version.
+ if options.use_xref_streams {
+ self.reference_table.cross_reference_type = XrefType::CrossReferenceStream;
+
+ if self.version.as_str() < "1.5" {
+ self.version = "1.5".to_string();
+ }
+ }
+
+ if options.use_object_streams {
+ self.save_with_object_streams(target, options)
+ } else {
+ self.save_internal(target)
+ }
+ }
+
+ /// Save PDF with modern features (object streams and cross-reference streams)
+ ///
+ /// An encrypted document is written without object streams. The objects are already
+ /// encrypted by the time they reach the writer and the file encryption key is gone,
+ /// so an object stream built here could only be written in the clear, contradicting
+ /// the document's `/Encrypt` dictionary. The requested cross-reference type is still
+ /// used; cross-reference streams are never encrypted.
+ pub fn save_modern<W: Write>(&mut self, target: &mut W) -> Result<()> {
+ let options = crate::SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: true,
+ ..Default::default()
+ };
+ self.save_with_options(target, options)
+ }
+
+ fn save_internal<W: Write>(&mut self, target: &mut W) -> Result<()> {
+ let mut target = CountingWrite {
+ inner: target,
+ bytes_written: 0,
+ };
+
+ let mut xref = Xref::new(self.max_id + 1, self.reference_table.cross_reference_type);
+ writeln!(target, "%PDF-{}", self.version)?;
+
+ Writer::write_binary_mark(&mut target, &self.binary_mark)?;
+
+ for (&(id, generation), object) in &self.objects {
+ if object
+ .type_name()
+ .map(|name| [b"ObjStm".as_slice(), b"XRef".as_slice(), b"Linearized".as_slice()].contains(&name))
+ .ok()
+ != Some(true)
+ {
+ Writer::write_indirect_object(&mut target, id, generation, object, &mut xref)?;
+ }
+ }
+
+ let xref_start = target.bytes_written;
+
+ // Pick right cross reference stream.
+ match xref.cross_reference_type {
+ XrefType::CrossReferenceTable => {
+ Writer::write_xref(&mut target, &xref)?;
+ self.write_trailer(&mut target)?;
+ }
+ XrefType::CrossReferenceStream => {
+ // Cross Reference Stream instead of XRef and Trailer
+ self.write_cross_reference_stream(&mut target, &mut xref, xref_start as u32)?;
+ }
+ }
+ // Write `startxref` part of trailer
+ write!(target, "\nstartxref\n{xref_start}\n%%EOF")?;
+
+ Ok(())
+ }
+
+ /// Save PDF with object streams enabled
+ fn save_with_object_streams<W: Write>(&mut self, target: &mut W, options: crate::SaveOptions) -> Result<()> {
+ use crate::ObjectStream;
+ use std::collections::HashMap;
+
+ // Ensure PDF version is at least 1.5 (required for object streams)
+ if self.version.as_str() < "1.5" {
+ self.version = "1.5".to_string();
+ }
+
+ // Object streams are built here, while serializing, but the document's objects were
+ // already encrypted by `Document::encrypt`, which drops the file encryption key once
+ // it is done. There is nothing left to encrypt a new stream with, so it would go out
+ // in the clear while the `/Encrypt` dictionary claims every stream is encrypted, and
+ // the strings packed into it would stay encrypted a second time: an object stream is
+ // itself the unit of encryption, and strings inside one shall not be encrypted
+ // separately. Write the objects out individually instead, as `save` does. The
+ // cross-reference type chosen in `save_with_options` still applies.
+ if self.is_encrypted() {
+ return self.save_internal(target);
+ }
+
+ let mut target = CountingWrite {
+ inner: target,
+ bytes_written: 0,
+ };
+
+ let mut xref = Xref::new(self.max_id + 1, self.reference_table.cross_reference_type);
+ writeln!(target, "%PDF-{}", self.version)?;
+ Writer::write_binary_mark(&mut target, &self.binary_mark)?;
+
+ // Organize objects into streams
+ let mut object_streams: Vec<crate::ObjectStream> = Vec::new();
+ let mut objects_to_write_directly = Vec::new();
+ let mut object_to_stream_map = HashMap::new();
+
+ // Categorize objects
+ for (&(id, generation), object) in &self.objects {
+ // Skip existing object streams - we'll create new ones
+ if let Object::Stream(stream) = object
+ && let Ok(type_obj) = stream.dict.get(b"Type")
+ && let Ok(type_name) = type_obj.as_name()
+ && type_name == b"ObjStm"
+ {
+ continue; // Skip existing object streams
+ }
+
+ if generation == 0 && ObjectStream::can_be_compressed((id, generation), object, self) {
+ // Object can be compressed
+ // Find or create an object stream for it
+ let stream_index = object_streams.len().saturating_sub(1);
+
+ if object_streams.is_empty()
+ || object_streams[stream_index].object_count()
+ >= options.object_stream_config.max_objects_per_stream
+ {
+ // Create new object stream
+ let new_stream = ObjectStream::builder()
+ .max_objects(options.object_stream_config.max_objects_per_stream)
+ .compression_level(options.object_stream_config.compression_level)
+ .build();
+ object_streams.push(new_stream);
+ }
+
+ let stream_index = object_streams.len() - 1;
+ object_streams[stream_index]
+ .add_object((id, generation), object.clone())
+ .ok();
+ object_to_stream_map.insert((id, generation), stream_index);
+ } else {
+ // Object must be written directly
+ objects_to_write_directly.push(((id, generation), object));
+ }
+ }
+
+ // Write direct objects first
+ for ((id, generation), object) in objects_to_write_directly {
+ Writer::write_indirect_object(&mut target, id, generation, object, &mut xref)?;
+ }
+
+ // Write object streams
+ let mut stream_count = 0;
+ for obj_stream in object_streams.into_iter() {
+ let stream_id = self.max_id + 1 + stream_count;
+ let stream_obj = obj_stream.to_stream_object().map_err(std::io::Error::other)?;
+
+ // Record compressed objects in xref
+ // Must use the same sort order as build_stream_content()
+ let mut sorted_objects: Vec<_> = obj_stream.objects.keys().cloned().collect();
+ sorted_objects.sort_by_key(|id| *id);
+ for (index_in_stream, (obj_id, _gen)) in sorted_objects.iter().enumerate() {
+ xref.insert(
+ *obj_id,
+ XrefEntry::Compressed {
+ container: stream_id,
+ index: index_in_stream as u16,
+ },
+ );
+ }
+
+ // Write the object stream
+ Writer::write_indirect_object(&mut target, stream_id, 0, &Object::Stream(stream_obj), &mut xref)?;
+ stream_count += 1;
+ }
+
+ // Update max_id to account for object streams
+ self.max_id += stream_count;
+
+ let xref_start = target.bytes_written;
+
+ // Write cross-reference
+ match xref.cross_reference_type {
+ XrefType::CrossReferenceTable => {
+ Writer::write_xref(&mut target, &xref)?;
+ self.write_trailer(&mut target)?;
+ }
+ XrefType::CrossReferenceStream => {
+ self.write_cross_reference_stream(&mut target, &mut xref, xref_start as u32)?;
+ }
+ }
+
+ write!(target, "\nstartxref\n{xref_start}\n%%EOF")?;
+ Ok(())
+ }
+
+ /// Write the Cross Reference Stream.
+ ///
+ /// Insert an `Object` to the end of the PDF (not visible when inspecting `Document`).
+ /// Note: This is different from the "Cross Reference Table".
+ fn write_cross_reference_stream<W: Write>(
+ &mut self, file: &mut CountingWrite<&mut W>, xref: &mut Xref, xref_start: u32,
+ ) -> Result<()> {
+ // Increment max_id to account for CRS.
+ self.max_id += 1;
+ let new_obj_id_for_crs = self.max_id;
+ xref.insert(
+ new_obj_id_for_crs,
+ XrefEntry::Normal {
+ offset: xref_start,
+ generation: 0,
+ },
+ );
+ self.trailer.set("Type", Name(b"XRef".to_vec()));
+ // Update `max_id` in trailer
+ self.trailer.set("Size", i64::from(self.max_id + 1));
+ // Set the size of each entry in bytes (default for PDFs is `[1 2 1]`)
+ // In our case we use `[u8, u32, u16]` for each entry
+ // to keep things simple and working at all times.
+ self.trailer.set("W", Array(vec![Integer(1), Integer(4), Integer(2)]));
+ // Note that `ASCIIHexDecode` does not work correctly,
+ // but is still useful for debugging sometimes.
+ let filter = XRefStreamFilter::None;
+ let (stream, stream_length, indexes) = Writer::create_xref_steam(xref, filter)?;
+ self.trailer.set("Index", indexes);
+
+ if filter == XRefStreamFilter::ASCIIHexDecode {
+ self.trailer.set("Filter", Name(b"ASCIIHexDecode".to_vec()));
+ } else {
+ self.trailer.remove(b"Filter");
+ }
+
+ self.trailer.set("Length", stream_length as i64);
+
+ let trailer = &self.trailer;
+ let cross_reference_stream = Stream(Stream {
+ dict: trailer.clone(),
+ allows_compression: true,
+ content: stream,
+ start_position: None,
+ });
+ // Insert Cross Reference Stream as an `Object` to the end of the PDF.
+ // The `Object` is not added to `Document` because it is generated every time you save.
+ Writer::write_indirect_object(file, new_obj_id_for_crs, 0, &cross_reference_stream, xref)?;
+
+ Ok(())
+ }
+
+ fn write_trailer(&mut self, file: &mut dyn Write) -> Result<()> {
+ self.trailer.set("Size", i64::from(self.max_id + 1));
+ file.write_all(b"trailer\n")?;
+ Writer::write_dictionary(file, &self.trailer)?;
+ Ok(())
+ }
+}
+
+impl IncrementalDocument {
+ /// Save PDF document to specified file path.
+ ///
+ /// The `check_incremental_save_supported` guard is invoked before
+ /// `File::create` so an unsupported input (e.g. a still-encrypted
+ /// previous revision) does not truncate a pre-existing file at `path`.
+ #[inline]
+ pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<File> {
+ self.check_incremental_save_supported()?;
+ let mut file = BufWriter::new(File::create(path)?);
+ self.save_internal(&mut file)?;
+ Ok(file.into_inner()?)
+ }
+
+ /// Save PDF to arbitrary target
+ #[inline]
+ pub fn save_to<W: Write>(&mut self, target: &mut W) -> Result<()> {
+ self.save_internal(target)
+ }
+
+ /// Reject the two cases we still cannot handle: a document that arrived
+ /// still-encrypted (no password was supplied), and the inconsistent case
+ /// of `encryption_state` set but `encrypt_object_id` missing (which should
+ /// not occur in practice — `decrypt_raw` records the id — but we guard
+ /// against it defensively).
+ fn check_incremental_save_supported(&self) -> Result<()> {
+ let prev = self.get_prev_documents();
+ if prev.is_encrypted() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "incremental update of a still-encrypted PDF is not supported: \
+ call `Document::decrypt` on the previous revision first \
+ (see https://github.com/J-F-Liu/lopdf/issues/520)",
+ ));
+ }
+ if let Some(state) = prev.encryption_state.as_ref()
+ && state.encrypt_object_id().is_none()
+ {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "cannot incrementally save this decrypted document: \
+ the /Encrypt object id was not recorded during decryption",
+ ));
+ }
+ Ok(())
+ }
+
+ fn save_internal<W: Write>(&mut self, target: &mut W) -> Result<()> {
+ self.check_incremental_save_supported()?;
+
+ // If the previous revision was encrypted (and successfully decrypted),
+ // we need to re-encrypt every appended object with the same encryption
+ // state and restore the trailer's `/Encrypt` reference.
+ //
+ // Cloning `EncryptionState` (small, mostly `Vec<u8>`) avoids borrow
+ // conflicts between `&self.prev_documents` and `&mut self.new_document`.
+ let encryption_state = self.get_prev_documents().encryption_state.as_ref().cloned();
+
+ let mut target = CountingWrite {
+ inner: target,
+ bytes_written: 0,
+ };
+
+ // Write previous document versions.
+ let prev_document_bytes = self.get_prev_documents_bytes();
+ target.inner.write_all(prev_document_bytes)?;
+ target.bytes_written += prev_document_bytes.len();
+
+ // Write/Append new document version.
+ let mut xref = Xref::new(
+ self.new_document.max_id + 1,
+ self.get_prev_documents().reference_table.cross_reference_type,
+ );
+
+ if let Some(last_byte) = prev_document_bytes.last()
+ && *last_byte != b'\n'
+ {
+ // Add a newline if it was not already present
+ writeln!(target)?;
+ }
+
+ // No file header and no binary marker here. An incremental update is
+ // defined (ISO 32000-1, 7.5.6) as the original file followed by the
+ // changed objects, a cross-reference section and a trailer — the
+ // header belongs to the file, which the previous revision already
+ // carries. Emitting a second "%PDF-x.y" makes the appended region
+ // look like the start of another document to anything that locates a
+ // PDF by scanning for the header, and because `new_document`'s
+ // version defaults to 1.4 it also understated the format of every
+ // file built on a later version.
+
+ // Write each newly added indirect object. When the document is
+ // encrypted, each object is cloned first and the clone is encrypted;
+ // the in-memory objects are left as plaintext so that further edits
+ // and repeated saves do not double-encrypt.
+ for (&(id, generation), object) in &self.new_document.objects {
+ if object
+ .type_name()
+ .map(|name| [b"ObjStm".as_slice(), b"XRef".as_slice(), b"Linearized".as_slice()].contains(&name))
+ .ok()
+ != Some(true)
+ {
+ if let Some(state) = encryption_state.as_ref() {
+ let mut encrypted = object.clone();
+ encryption::encrypt_object(state, (id, generation), &mut encrypted)
+ .map_err(std::io::Error::other)?;
+ Writer::write_indirect_object(&mut target, id, generation, &encrypted, &mut xref)?;
+ } else {
+ Writer::write_indirect_object(&mut target, id, generation, object, &mut xref)?;
+ }
+ }
+ }
+
+ // For an encrypted document, install a modified copy of the trailer
+ // that restores the /Encrypt reference. We swap it in temporarily so
+ // that `write_trailer` / `write_cross_reference_stream` — which
+ // already mutate the trailer to update Size/W/Length/etc — operate
+ // on the modified copy, and swap it back afterwards so that the
+ // in-memory `new_document.trailer` stays clean for subsequent saves.
+ let saved_trailer = if let Some(state) = encryption_state.as_ref() {
+ let encrypt_id = state
+ .encrypt_object_id()
+ .expect("encrypt_object_id presence checked by check_incremental_save_supported");
+ let mut modified = self.new_document.trailer.clone();
+ modified.set(b"Encrypt", Object::Reference(encrypt_id));
+ Some(std::mem::replace(&mut self.new_document.trailer, modified))
+ } else {
+ None
+ };
+
+ let xref_start = target.bytes_written;
+
+ // Pick right cross reference stream.
+ let write_result: Result<()> = (|| {
+ match xref.cross_reference_type {
+ XrefType::CrossReferenceTable => {
+ Writer::write_xref(&mut target, &xref)?;
+ self.new_document.write_trailer(&mut target)?;
+ }
+ XrefType::CrossReferenceStream => {
+ // Cross Reference Stream instead of XRef and Trailer
+ self.new_document
+ .write_cross_reference_stream(&mut target, &mut xref, xref_start as u32)?;
+ }
+ }
+ // Write `startxref` part of trailer
+ write!(target, "\nstartxref\n{xref_start}\n%%EOF")?;
+ Ok(())
+ })();
+
+ // Restore the original in-memory trailer even if writing failed.
+ if let Some(saved) = saved_trailer {
+ self.new_document.trailer = saved;
+ }
+
+ write_result
+ }
+}
+
+pub struct Writer;
+
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+pub enum XRefStreamFilter {
+ ASCIIHexDecode,
+ _FlateDecode, //this is generally a Zlib compressed Stream.
+ None,
+}
+
+impl Writer {
+ fn need_separator(object: &Object) -> bool {
+ matches!(*object, Null | Boolean(_) | Integer(_) | Real(_) | Reference(_))
+ }
+
+ fn need_end_separator(object: &Object) -> bool {
+ matches!(
+ *object,
+ Null | Boolean(_) | Integer(_) | Real(_) | Name(_) | Reference(_) | Object::Stream(_)
+ )
+ }
+
+ /// Write Cross Reference Table.
+ ///
+ /// Note: This is different from a "Cross Reference Stream".
+ fn write_xref(file: &mut dyn Write, xref: &Xref) -> Result<()> {
+ writeln!(file, "xref")?;
+
+ let mut xref_section = XrefSection::new(0);
+ // Add first (0) entry
+ xref_section.add_unusable_free_entry();
+
+ // Iterate over the actual highest entry instead of `xref.size`:
+ // `size` is fixed before object streams (and the xref stream itself)
+ // are appended, so entries past it would never reach the table.
+ for obj_id in 1..=xref.max_id() {
+ if let Some(entry) = xref.get(obj_id) {
+ // A section starts at the first *present* id; starting it at
+ // a missing id would shift every subsequent entry by one.
+ if xref_section.is_empty() {
+ xref_section = XrefSection::new(obj_id);
+ }
+ match *entry {
+ XrefEntry::Normal { offset, generation } => {
+ // Add entry
+ xref_section.add_entry(XrefEntry::Normal { offset, generation });
+ }
+ XrefEntry::Compressed { container: _, index: _ } => {
+ xref_section.add_unusable_free_entry();
+ }
+ XrefEntry::Free => {
+ xref_section.add_entry(XrefEntry::Free);
+ }
+ XrefEntry::UnusableFree => {
+ xref_section.add_unusable_free_entry();
+ }
+ }
+ } else {
+ // Skip over `obj_id`, but finish section if not empty.
+ if !xref_section.is_empty() {
+ xref_section.write_xref_section(file)?;
+ xref_section = XrefSection::new(0);
+ }
+ }
+ }
+ // Print last section
+ if !xref_section.is_empty() {
+ xref_section.write_xref_section(file)?;
+ }
+ Ok(())
+ }
+
+ /// Create stream for Cross reference stream.
+ fn create_xref_steam(xref: &Xref, filter: XRefStreamFilter) -> Result<(Vec<u8>, usize, Object)> {
+ let mut xref_sections = Vec::new();
+ let mut xref_section = XrefSection::new(0);
+
+ // Iterate over the actual highest entry instead of `xref.size`:
+ // `size` is fixed before object streams (and the xref stream itself)
+ // are appended, so entries past it would never reach the stream.
+ for obj_id in 1..=xref.max_id() {
+ if let Some(entry) = xref.get(obj_id) {
+ // A section starts at the first *present* id; starting it at
+ // a missing id would shift every subsequent entry by one.
+ if xref_section.is_empty() {
+ xref_section = XrefSection::new(obj_id);
+ }
+ xref_section.add_entry(entry.clone());
+ } else {
+ // Skip over but finish section if not empty
+ if !xref_section.is_empty() {
+ xref_sections.push(xref_section);
+ xref_section = XrefSection::new(0);
+ }
+ }
+ }
+ // Print last section
+ if !xref_section.is_empty() {
+ xref_sections.push(xref_section);
+ }
+
+ let mut xref_stream = Vec::new();
+ let mut xref_index = Vec::new();
+
+ for section in xref_sections {
+ // Add indexes to list
+ xref_index.push(Integer(section.starting_id as i64));
+ xref_index.push(Integer(section.entries.len() as i64));
+ // Add entries to stream
+ for (obj_id, entry) in (section.starting_id..).zip(section.entries) {
+ match entry {
+ XrefEntry::Free => {
+ // Type 0
+ xref_stream.push(0);
+ xref_stream.extend(obj_id.to_be_bytes());
+ xref_stream.extend(vec![0, 0]); // TODO add generation number
+ }
+ XrefEntry::UnusableFree => {
+ // Type 0
+ xref_stream.push(0);
+ xref_stream.extend(obj_id.to_be_bytes());
+ xref_stream.extend(65535_u16.to_be_bytes());
+ }
+ XrefEntry::Normal { offset, generation } => {
+ // Type 1
+ xref_stream.push(1);
+ xref_stream.extend(offset.to_be_bytes());
+ xref_stream.extend(generation.to_be_bytes());
+ }
+ XrefEntry::Compressed { container, index } => {
+ // Type 2
+ xref_stream.push(2);
+ xref_stream.extend(container.to_be_bytes());
+ xref_stream.extend(index.to_be_bytes());
+ }
+ }
+ }
+ }
+
+ // The end of line character should not be counted, added later.
+ let stream_length = xref_stream.len();
+
+ if filter == XRefStreamFilter::ASCIIHexDecode {
+ xref_stream = xref_stream
+ .iter()
+ .flat_map(|c| format!("{c:02X}").as_bytes().to_vec())
+ .collect::<Vec<u8>>();
+ }
+
+ Ok((xref_stream, stream_length, Array(xref_index)))
+ }
+
+ fn write_indirect_object<W: Write>(
+ file: &mut CountingWrite<&mut W>, id: u32, generation: u16, object: &Object, xref: &mut Xref,
+ ) -> Result<()> {
+ let offset = file.bytes_written as u32;
+ xref.insert(id, XrefEntry::Normal { offset, generation });
+ write!(
+ file,
+ "{} {} obj\n{}",
+ id,
+ generation,
+ if Writer::need_separator(object) { " " } else { "" }
+ )?;
+ Writer::write_object(file, object)?;
+ writeln!(
+ file,
+ "{}\nendobj",
+ if Writer::need_end_separator(object) { " " } else { "" }
+ )?;
+ Ok(())
+ }
+
+ pub fn write_object(file: &mut dyn Write, object: &Object) -> Result<()> {
+ match object {
+ Null => file.write_all(b"null"),
+ Boolean(value) => {
+ if *value {
+ file.write_all(b"true")
+ } else {
+ file.write_all(b"false")
+ }
+ }
+ Integer(value) => {
+ let mut buf = itoa::Buffer::new();
+ file.write_all(buf.format(*value).as_bytes())
+ }
+ Real(value) => write!(file, "{value}"),
+ Name(name) => Writer::write_name(file, name),
+ String(text, format) => Writer::write_string(file, text, format),
+ Array(array) => Writer::write_array(file, array),
+ Object::Dictionary(dict) => Writer::write_dictionary(file, dict),
+ Object::Stream(stream) => Writer::write_stream(file, stream),
+ Reference(id) => write!(file, "{} {} R", id.0, id.1),
+ }
+ }
+
+ fn write_name(file: &mut dyn Write, name: &[u8]) -> Result<()> {
+ file.write_all(b"/")?;
+ for &byte in name {
+ // white-space and delimiter chars are encoded to # sequences
+ // also encode bytes outside of the range 33 (!) to 126 (~)
+ if b" \t\n\r\x0C()<>[]{}/%#".contains(&byte) || !(33..=126).contains(&byte) {
+ write!(file, "#{byte:02X}")?;
+ } else {
+ file.write_all(&[byte])?;
+ }
+ }
+ Ok(())
+ }
+
+ fn write_string(file: &mut dyn Write, text: &[u8], format: &StringFormat) -> Result<()> {
+ match *format {
+ // Within a Literal string, backslash (\) and unbalanced parentheses should be escaped.
+ // This rule apply to each individual byte in a string object,
+ // whether the string is interpreted as single-byte or multiple-byte character codes.
+ // If an end-of-line marker appears within a literal string without a preceding backslash, the result is
+ // equivalent to \n. So \r also need be escaped.
+ StringFormat::Literal => {
+ let mut escape_indice = Vec::new();
+ let mut parentheses = Vec::new();
+ for (index, &byte) in text.iter().enumerate() {
+ match byte {
+ b'(' => parentheses.push(index),
+ b')' => {
+ if !parentheses.is_empty() {
+ parentheses.pop();
+ } else {
+ escape_indice.push(index);
+ }
+ }
+ b'\\' | b'\r' => escape_indice.push(index),
+ _ => continue,
+ }
+ }
+ escape_indice.append(&mut parentheses);
+
+ file.write_all(b"(")?;
+ if !escape_indice.is_empty() {
+ for (index, &byte) in text.iter().enumerate() {
+ if escape_indice.contains(&index) {
+ file.write_all(b"\\")?;
+ file.write_all(&[if byte == b'\r' { b'r' } else { byte }])?;
+ } else {
+ file.write_all(&[byte])?;
+ }
+ }
+ } else {
+ file.write_all(text)?;
+ }
+ file.write_all(b")")?;
+ }
+ StringFormat::Hexadecimal => {
+ file.write_all(b"<")?;
+ for &byte in text {
+ write!(file, "{byte:02X}")?;
+ }
+ file.write_all(b">")?;
+ }
+ }
+ Ok(())
+ }
+
+ fn write_array(file: &mut dyn Write, array: &[Object]) -> Result<()> {
+ file.write_all(b"[")?;
+ let mut first = true;
+ for object in array {
+ if first {
+ first = false;
+ } else if Writer::need_separator(object) {
+ file.write_all(b" ")?;
+ }
+ Writer::write_object(file, object)?;
+ }
+ file.write_all(b"]")?;
+ Ok(())
+ }
+
+ fn write_dictionary(file: &mut dyn Write, dictionary: &Dictionary) -> Result<()> {
+ file.write_all(b"<<")?;
+ for (key, value) in dictionary {
+ Writer::write_name(file, key)?;
+ if Writer::need_separator(value) {
+ file.write_all(b" ")?;
+ }
+ Writer::write_object(file, value)?;
+ }
+ file.write_all(b">>")?;
+ Ok(())
+ }
+
+ fn write_stream(file: &mut dyn Write, stream: &Stream) -> Result<()> {
+ Writer::write_dictionary(file, &stream.dict)?;
+ file.write_all(b"stream\n")?;
+ file.write_all(&stream.content)?;
+ file.write_all(b"\nendstream")?;
+ Ok(())
+ }
+
+ /// Write Binary mark as follows: %{binary_mark[4]}\n -> %Ç쏢 or Hex(%25 c3 87 c3 ac)
+ ///
+ /// Note: Specified in ISO 19005-2:2011, ISO 19005-3:2012
+ /// headerByte1 > 127 && headerByte2 > 127 && headerByte3 > 127 && headerByte4 > 127
+ fn write_binary_mark(file: &mut dyn Write, binary_mark: &[u8]) -> Result<()> {
+ if binary_mark.iter().all(|&byte| byte >= 128) {
+ file.write_all(b"%")?;
+ file.write_all(binary_mark)?;
+ file.write_all(b"\n")?;
+ } else {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "Invalid binary mark",
+ ));
+ }
+
+ Ok(())
+ }
+}
+
+pub struct CountingWrite<W: Write> {
+ inner: W,
+ bytes_written: usize,
+}
+
+impl<W: Write> Write for CountingWrite<W> {
+ #[inline]
+ fn write(&mut self, buffer: &[u8]) -> Result<usize> {
+ let result = self.inner.write(buffer);
+ if let Ok(bytes) = result {
+ self.bytes_written += bytes;
+ }
+ result
+ }
+
+ #[inline]
+ fn write_all(&mut self, buffer: &[u8]) -> Result<()> {
+ self.bytes_written += buffer.len();
+ // If this returns `Err` we can’t know how many bytes were actually written (if any)
+ // but that doesn’t matter since we’re gonna abort the entire PDF generation anyway.
+ self.inner.write_all(buffer)
+ }
+
+ #[inline]
+ fn flush(&mut self) -> Result<()> {
+ self.inner.flush()
+ }
+}
+
+#[test]
+fn save_document() {
+ let mut doc = Document::with_version("1.5");
+ doc.objects.insert((1, 0), Null);
+ doc.objects.insert((2, 0), Boolean(true));
+ doc.objects.insert((3, 0), Integer(3));
+ doc.objects.insert((4, 0), Real(0.5));
+ doc.objects
+ .insert((5, 0), String("text((\r)".as_bytes().to_vec(), StringFormat::Literal));
+ doc.objects.insert(
+ (6, 0),
+ String("text((\r)".as_bytes().to_vec(), StringFormat::Hexadecimal),
+ );
+ doc.objects.insert((7, 0), Name(b"name \t".to_vec()));
+ doc.objects.insert((8, 0), Reference((1, 0)));
+ doc.objects
+ .insert((9, 2), Array(vec![Integer(1), Integer(2), Integer(3)]));
+ doc.objects
+ .insert((11, 0), Stream(Stream::new(Dictionary::new(), vec![0x41, 0x42, 0x43])));
+ let mut dict = Dictionary::new();
+ dict.set("A", Null);
+ dict.set("B", false);
+ dict.set("C", Name(b"name".to_vec()));
+ doc.objects.insert((12, 0), Object::Dictionary(dict));
+ doc.max_id = 12;
+
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir().unwrap();
+ let file_path = temp_dir.path().join("test_0_save.pdf");
+ doc.save(&file_path).unwrap();
+ // Check if file was created.
+ assert!(file_path.exists());
+ // Check if path is file
+ assert!(file_path.is_file());
+ // Check if the file is above 400 bytes (should be about 610 bytes)
+ assert!(file_path.metadata().unwrap().len() > 400);
+}
diff --git a/vendor/lopdf/src/xobject.rs b/vendor/lopdf/src/xobject.rs
new file mode 100644
index 000000000..fa6512d6e
--- /dev/null
+++ b/vendor/lopdf/src/xobject.rs
@@ -0,0 +1,259 @@
+use crate::*;
+use crate::{Dictionary, Stream};
+
+#[cfg(feature = "embed_image")]
+use image::{self, ColorType, ImageFormat};
+
+#[cfg(feature = "embed_image")]
+use std::path::Path;
+
+#[cfg(feature = "embed_image")]
+use crate::Result;
+
+#[derive(Debug, Clone)]
+pub struct PdfImage<'a> {
+ pub id: ObjectId,
+ pub width: i64,
+ pub height: i64,
+ pub color_space: Option<String>,
+ pub filters: Option<Vec<String>>,
+ pub bits_per_component: Option<i64>,
+ /// Image Data
+ pub content: &'a [u8],
+ /// Origin Stream Dictionary
+ pub origin_dict: &'a Dictionary,
+}
+
+pub fn form(boundingbox: Vec<f32>, matrix: Vec<f32>, content: Vec<u8>) -> Stream {
+ let mut dict = Dictionary::new();
+ dict.set("Type", Object::Name(b"XObject".to_vec()));
+ dict.set("Subtype", Object::Name(b"Form".to_vec()));
+ dict.set(
+ "BBox",
+ Object::Array(boundingbox.into_iter().map(Object::Real).collect()),
+ );
+ dict.set("Matrix", Object::Array(matrix.into_iter().map(Object::Real).collect()));
+ let mut xobject = Stream::new(dict, content);
+ // Ignore any compression error.
+ let _ = xobject.compress();
+ xobject
+}
+
+#[cfg(feature = "embed_image")]
+pub fn image<P: AsRef<Path>>(path: P) -> Result<Stream> {
+ use std::fs::File;
+ use std::io::prelude::*;
+
+ let mut file = File::open(&path)?;
+ let mut buffer = Vec::new();
+ file.read_to_end(&mut buffer)?;
+
+ image_from(buffer)
+}
+
+#[cfg(feature = "embed_image")]
+pub fn image_from(buffer: Vec<u8>) -> Result<Stream> {
+ let ((width, height), color_type) = get_dimensions_and_color_type(&buffer)?;
+
+ let (bpc, color_space) = match color_type {
+ // 8-bit per channel types
+ ColorType::L8 => (8, b"DeviceGray".to_vec()),
+ ColorType::La8 => (8, b"DeviceGray".to_vec()),
+ ColorType::Rgb8 => (8, b"DeviceRGB".to_vec()),
+ ColorType::Rgba8 => (8, b"DeviceRGB".to_vec()),
+ // 16-bit per channel types
+ ColorType::L16 => (16, b"DeviceGray".to_vec()),
+ ColorType::La16 => (16, b"DeviceGray".to_vec()),
+ ColorType::Rgb16 => (16, b"DeviceRGB".to_vec()),
+ ColorType::Rgba16 => (16, b"DeviceRGB".to_vec()),
+ // f32 not supported, maybe JPXDecode?
+ ColorType::Rgb32F => return Err(Error::Unimplemented("ColorType::Rgb32F is not supported")),
+ ColorType::Rgba32F => return Err(Error::Unimplemented("ColorType::Rgba32F is not supported")),
+ // The above ColorType is all the types currently supported by the image crate
+ // But ColorType is #[non_exhaustive], there may be new types supported in the future
+ _ => {
+ return Err(Error::Unimplemented(
+ "The image crate supports a new color type, but lopdf has not been updated yet",
+ ));
+ }
+ };
+
+ let mut dict = Dictionary::new();
+ dict.set("Type", Object::Name(b"XObject".to_vec()));
+ dict.set("Subtype", Object::Name(b"Image".to_vec()));
+ dict.set("Width", width);
+ dict.set("Height", height);
+ dict.set("ColorSpace", Object::Name(color_space));
+ dict.set("BitsPerComponent", bpc);
+
+ let format = image::guess_format(&buffer)?;
+ if format == ImageFormat::Jpeg {
+ // JPEG do not need to be decoded
+ dict.set("Filter", Object::Name(b"DCTDecode".to_vec()));
+ Ok(Stream::new(dict, buffer))
+ } else {
+ // Other formats need to be decoded
+ let img = image::load_from_memory(&buffer)?;
+ let content = match img.color() {
+ // can be used directly
+ ColorType::L8 => img.into_bytes(),
+ // need to remove alpha channel
+ ColorType::La8 => img.into_luma8().into_raw(),
+ // can be used directly
+ ColorType::Rgb8 => img.into_bytes(),
+ // need to remove alpha channel
+ ColorType::Rgba8 => img.into_rgb8().into_raw(),
+ // need to convert each 16-bit pixel to big-endian bytes
+ ColorType::L16 => img
+ .into_luma16()
+ .into_raw()
+ .iter()
+ .flat_map(|&pixel| pixel.to_be_bytes()) // convert each 16-bit pixel to big-endian bytes
+ .collect(),
+ // need to remove alpha channel, then convert each 16-bit pixel to big-endian bytes
+ ColorType::La16 => img
+ .into_luma16() // remove alpha channel
+ .into_raw()
+ .iter()
+ .flat_map(|&pixel| pixel.to_be_bytes()) // convert each 16-bit pixel to big-endian bytes
+ .collect(),
+ // need to convert each 16-bit pixel to big-endian bytes
+ ColorType::Rgb16 => img
+ .into_rgb16()
+ .into_raw()
+ .iter()
+ .flat_map(|&pixel| pixel.to_be_bytes()) // convert each 16-bit pixel to big-endian bytes
+ .collect(),
+ // need to remove alpha channel, then convert each 16-bit pixel to big-endian bytes
+ ColorType::Rgba16 => img
+ .into_rgb16() // remove alpha channel
+ .into_raw()
+ .iter()
+ .flat_map(|&pixel| pixel.to_be_bytes()) // convert each 16-bit pixel to big-endian bytes
+ .collect(),
+ // f32 not supported, maybe JPXDecode?
+ ColorType::Rgb32F => return Err(Error::Unimplemented("ColorType::Rgb32F is not supported")),
+ ColorType::Rgba32F => return Err(Error::Unimplemented("ColorType::Rgba32F is not supported")),
+ // The above ColorType is all the types currently supported by the image crate
+ // But ColorType is #[non_exhaustive], there may be new types supported in the future
+ _ => {
+ return Err(Error::Unimplemented(
+ "The image library supports a new color type, but lopdf has not been updated yet",
+ ));
+ }
+ };
+
+ let mut img_object = Stream::new(dict, content);
+ // Ignore any compression error.
+ let _ = img_object.compress();
+ Ok(img_object)
+ }
+}
+
+/// Get the `dimensions` and `color type` without decode, for performance
+#[cfg(feature = "embed_image")]
+fn get_dimensions_and_color_type(buffer: &Vec<u8>) -> Result<((u32, u32), ColorType)> {
+ use image::{ImageDecoder, ImageReader};
+
+ let reader = ImageReader::new(std::io::Cursor::new(buffer));
+ let decoder = reader.with_guessed_format()?.into_decoder()?;
+
+ let dimensions = decoder.dimensions();
+ let color_type = decoder.color_type();
+
+ Ok((dimensions, color_type))
+}
+
+#[cfg(all(feature = "embed_image", not(feature = "async")))]
+#[test]
+fn insert_image() {
+ use super::xobject;
+ let mut doc = Document::load("assets/example.pdf").unwrap();
+ let pages = doc.get_pages();
+ let page_id = *pages.get(&1).expect(&format!("Page {} not exist.", 1));
+ let img = xobject::image("assets/pdf_icon.jpg").unwrap();
+ doc.insert_image(page_id, img, (100.0, 210.0), (400.0, 225.0)).unwrap();
+ doc.save("test_5_image.pdf").unwrap();
+}
+
+#[cfg(all(feature = "embed_image", feature = "async"))]
+#[tokio::test]
+async fn insert_image() {
+ use super::xobject;
+ let mut doc = Document::load("assets/example.pdf").await.unwrap();
+ let pages = doc.get_pages();
+ let page_id = *pages.get(&1).unwrap_or_else(|| panic!("Page {} not exist.", 1));
+ let img = xobject::image("assets/pdf_icon.jpg").unwrap();
+ doc.insert_image(page_id, img, (100.0, 210.0), (400.0, 225.0)).unwrap();
+ doc.save("test_5_image.pdf").unwrap();
+}
+
+#[cfg(feature = "embed_image")]
+#[test]
+fn embed_supported_color_type() -> Result<()> {
+ use content::{Content, Operation};
+ use image::GenericImageView;
+
+ let mut img_paths = std::fs::read_dir("assets/supported_color_type")?
+ .filter_map(|entry| entry.ok())
+ .map(|entry| entry.path())
+ .collect::<Vec<_>>();
+ // sort by file name
+ img_paths.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
+
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+ let mut page_ids = vec![];
+
+ for img_path in img_paths {
+ let img = image::open(&img_path)?;
+ let (width, height) = img.dimensions();
+ let color_type = img.color();
+ println!("Image: {img_path:?}, width: {width}, height: {height}, color type: {color_type:?}");
+
+ let image_stream = xobject::image(img_path)?;
+
+ let img_id = doc.add_object(image_stream);
+ let img_name = format!("X{}", img_id.0);
+
+ let cm_operation = Operation::new(
+ "cm",
+ vec![width.into(), 0.into(), 0.into(), height.into(), 0.into(), 0.into()],
+ );
+
+ let do_operation = Operation::new("Do", vec![Object::Name(img_name.as_bytes().to_vec())]);
+ let content = Content {
+ operations: vec![cm_operation, do_operation],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "MediaBox" => vec![0.into(), 0.into(), width.into(), height.into()],
+ });
+
+ doc.add_xobject(page_id, img_name.as_bytes(), img_id)?;
+ // add page to doc
+ page_ids.push(page_id);
+ }
+
+ let pages_dict = dictionary! {
+ "Type" => "Pages",
+ "Count" => page_ids.len() as u32,
+ "Kids" => page_ids.into_iter().map(Object::Reference).collect::<Vec<_>>(),
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ doc.compress();
+
+ doc.save("supported_color_type.pdf")?;
+ Ok(())
+}
diff --git a/vendor/lopdf/src/xref.rs b/vendor/lopdf/src/xref.rs
new file mode 100644
index 000000000..8d10dca4b
--- /dev/null
+++ b/vendor/lopdf/src/xref.rs
@@ -0,0 +1,314 @@
+use std::collections::BTreeMap;
+use std::io::{Result, Write};
+
+#[derive(Debug, Clone)]
+pub struct Xref {
+ /// Type of Cross-Reference used in the last incremental version.
+ /// This method of cross-referencing will also be used when saving the file.
+ /// PDFs with Incremental Updates should alway use the same cross-reference type.
+ pub cross_reference_type: XrefType,
+
+ /// Entries for indirect object.
+ pub entries: BTreeMap<u32, XrefEntry>,
+
+ /// Total number of entries (including free entries), equal to the highest object number plus 1.
+ pub size: u32,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub enum XrefType {
+ /// Cross-Reference Streams are supported beginning with PDF 1.5.
+ CrossReferenceStream,
+ /// Cross-Reference Table is older but still frequently used.
+ CrossReferenceTable,
+}
+
+#[derive(Debug, Clone)]
+pub enum XrefEntry {
+ Free, // TODO add generation number
+ UnusableFree,
+ Normal { offset: u32, generation: u16 },
+ Compressed { container: u32, index: u16 },
+}
+
+#[derive(Debug, Clone)]
+pub struct XrefSection {
+ pub starting_id: u32,
+ pub entries: Vec<XrefEntry>,
+}
+
+impl Xref {
+ pub fn new(size: u32, xref_type: XrefType) -> Xref {
+ Xref {
+ cross_reference_type: xref_type,
+ entries: BTreeMap::new(),
+ size,
+ }
+ }
+
+ pub fn get(&self, id: u32) -> Option<&XrefEntry> {
+ self.entries.get(&id)
+ }
+
+ pub fn insert(&mut self, id: u32, entry: XrefEntry) {
+ self.entries.insert(id, entry);
+ self.size = self.size.max(id.saturating_add(1));
+ }
+
+ /// Combine Xref entries. Only add them if they do not exists already.
+ /// Do not replace existing entries.
+ pub fn merge(&mut self, xref: Xref) {
+ for (id, entry) in xref.entries {
+ self.entries.entry(id).or_insert(entry);
+ }
+ }
+
+ pub fn clear(&mut self) {
+ self.entries.clear()
+ }
+
+ pub fn max_id(&self) -> u32 {
+ match self.entries.keys().max() {
+ Some(&id) => id,
+ None => 0,
+ }
+ }
+}
+
+impl XrefEntry {
+ pub fn is_normal(&self) -> bool {
+ matches!(*self, XrefEntry::Normal { .. })
+ }
+
+ pub fn is_compressed(&self) -> bool {
+ matches!(*self, XrefEntry::Compressed { .. })
+ }
+
+ /// Encode entry for use in cross-reference stream
+ pub fn encode_for_xref_stream(&self, widths: &[usize; 3]) -> Vec<u8> {
+ let mut result = Vec::new();
+
+ match self {
+ XrefEntry::Free | XrefEntry::UnusableFree => {
+ // Type 0: Free object
+ encode_field(0, widths[0], &mut result);
+ encode_field(0, widths[1], &mut result); // Next free object
+ encode_field(0, widths[2], &mut result); // Generation
+ }
+ XrefEntry::Normal { offset, generation } => {
+ // Type 1: Uncompressed object
+ encode_field(1, widths[0], &mut result);
+ encode_field(*offset as u64, widths[1], &mut result);
+ encode_field(*generation as u64, widths[2], &mut result);
+ }
+ XrefEntry::Compressed { container, index } => {
+ // Type 2: Compressed object
+ encode_field(2, widths[0], &mut result);
+ encode_field(*container as u64, widths[1], &mut result);
+ encode_field(*index as u64, widths[2], &mut result);
+ }
+ }
+
+ result
+ }
+
+ /// Write Entry in Cross Reference Table.
+ pub fn write_xref_entry(&self, file: &mut dyn Write) -> Result<()> {
+ match self {
+ XrefEntry::Normal { offset, generation } => {
+ writeln!(file, "{offset:>010} {generation:>05} n ")?;
+ }
+ XrefEntry::Compressed { container: _, index: _ } => {
+ writeln!(file, "{:>010} {:>05} f ", 0, 65535)?;
+ }
+ XrefEntry::Free => {
+ writeln!(file, "{:>010} {:>05} f ", 0, 0)?;
+ }
+ XrefEntry::UnusableFree => {
+ writeln!(file, "{:>010} {:>05} f ", 0, 65535)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+impl XrefSection {
+ pub fn new(starting_id: u32) -> Self {
+ XrefSection {
+ starting_id,
+ entries: Vec::new(),
+ }
+ }
+
+ pub fn add_entry(&mut self, entry: XrefEntry) {
+ self.entries.push(entry);
+ }
+
+ pub fn add_unusable_free_entry(&mut self) {
+ self.add_entry(XrefEntry::UnusableFree);
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+
+ /// Write Section in Cross Reference Table.
+ pub fn write_xref_section(&self, file: &mut dyn Write) -> Result<()> {
+ if !self.is_empty() {
+ // Write section range
+ writeln!(file, "{} {}", self.starting_id, self.entries.len())?;
+ // Write entries
+ for entry in &self.entries {
+ entry.write_xref_entry(file)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+pub use crate::parser_aux::{decode_xref_stream, decode_xref_stream_with_limit};
+
+/// Encode a field value as big-endian bytes with specified width
+fn encode_field(value: u64, width: usize, output: &mut Vec<u8>) {
+ for i in (0..width).rev() {
+ output.push((value >> (i * 8)) as u8);
+ }
+}
+
+/// Builder for creating cross-reference streams
+pub struct XrefStreamBuilder<'a> {
+ xref: &'a Xref,
+ entries: Vec<(u32, &'a XrefEntry)>,
+ widths: [usize; 3],
+}
+
+impl<'a> XrefStreamBuilder<'a> {
+ /// Create a new builder from an Xref
+ pub fn new(xref: &'a Xref) -> Self {
+ let entries: Vec<_> = xref.entries.iter().map(|(&id, entry)| (id, entry)).collect();
+
+ Self {
+ xref,
+ entries,
+ widths: [1, 2, 2], // Default widths
+ }
+ }
+
+ /// Get the number of entries
+ pub fn entries_count(&self) -> usize {
+ self.entries.len()
+ }
+
+ /// Calculate optimal field widths based on the data
+ pub fn calculate_optimal_widths(&self) -> [usize; 3] {
+ let mut max_offset = 0u64;
+ let mut max_gen = 0u16;
+ let mut max_container = 0u32;
+ let mut max_index = 0u16;
+
+ for (_, entry) in &self.entries {
+ match entry {
+ XrefEntry::Normal { offset, generation } => {
+ max_offset = max_offset.max(*offset as u64);
+ max_gen = max_gen.max(*generation);
+ }
+ XrefEntry::Compressed { container, index } => {
+ max_container = max_container.max(*container);
+ max_index = max_index.max(*index);
+ }
+ _ => {}
+ }
+ }
+
+ // Calculate bytes needed
+ let offset_bytes = bytes_needed(max_offset);
+ let gen_bytes = bytes_needed(max_gen as u64);
+ let container_bytes = bytes_needed(max_container as u64);
+ let index_bytes = bytes_needed(max_index as u64);
+
+ [
+ 1, // Type field is always 1 byte
+ offset_bytes.max(container_bytes),
+ gen_bytes.max(index_bytes),
+ ]
+ }
+
+ /// Build the stream content
+ pub fn build_stream_content(&mut self) -> crate::Result<Vec<u8>> {
+ self.widths = self.calculate_optimal_widths();
+ let mut content = Vec::new();
+
+ // Sort entries by ID
+ self.entries.sort_by_key(|(id, _)| *id);
+
+ for (_, entry) in &self.entries {
+ let encoded = entry.encode_for_xref_stream(&self.widths);
+ content.extend_from_slice(&encoded);
+ }
+
+ Ok(content)
+ }
+
+ /// Build the Index array for the cross-reference stream
+ pub fn build_index_array(&self) -> Vec<crate::Object> {
+ use crate::Object;
+
+ let mut index = Vec::new();
+ let mut sorted_entries = self.entries.clone();
+ sorted_entries.sort_by_key(|(id, _)| *id);
+
+ if sorted_entries.is_empty() {
+ return index;
+ }
+
+ let mut start = sorted_entries[0].0;
+ let mut count = 1;
+
+ for i in 1..sorted_entries.len() {
+ if sorted_entries[i].0 == sorted_entries[i - 1].0 + 1 {
+ count += 1;
+ } else {
+ index.push(Object::Integer(start as i64));
+ index.push(Object::Integer(count as i64));
+ start = sorted_entries[i].0;
+ count = 1;
+ }
+ }
+
+ index.push(Object::Integer(start as i64));
+ index.push(Object::Integer(count as i64));
+
+ index
+ }
+
+ /// Convert to a Stream object
+ pub fn to_stream_object(&mut self) -> crate::Result<crate::Stream> {
+ use crate::{Object, Stream, dictionary};
+
+ let content = self.build_stream_content()?;
+ let dict = dictionary! {
+ "Type" => "XRef",
+ "Size" => self.xref.size as i64,
+ "W" => vec![
+ Object::Integer(self.widths[0] as i64),
+ Object::Integer(self.widths[1] as i64),
+ Object::Integer(self.widths[2] as i64),
+ ],
+ "Index" => self.build_index_array(),
+ "Filter" => "FlateDecode"
+ };
+
+ let mut stream = Stream::new(dict, content);
+ stream.compress()?;
+ Ok(stream)
+ }
+}
+
+/// Calculate the minimum number of bytes needed to represent a value
+fn bytes_needed(value: u64) -> usize {
+ if value == 0 {
+ 1
+ } else {
+ (64 - value.leading_zeros()).div_ceil(8) as usize
+ }
+}
diff --git a/vendor/lopdf/tests/annotation.rs b/vendor/lopdf/tests/annotation.rs
new file mode 100644
index 000000000..9c072828b
--- /dev/null
+++ b/vendor/lopdf/tests/annotation.rs
@@ -0,0 +1,100 @@
+use lopdf::{Document, Object, Result, dictionary};
+
+mod utils;
+
+/// One page whose `/Annots` mixes the two legal entry forms: a reference to
+/// an annotation dictionary, and the dictionary written directly into the
+/// array. Returns the document and the page's id.
+fn page_with_mixed_annots(annots_indirect: bool) -> (Document, lopdf::ObjectId) {
+ let mut doc = Document::with_version("1.7");
+ let referenced = doc.add_object(dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Contents" => Object::string_literal("referenced"),
+ });
+ let entries = vec![
+ Object::Reference(referenced),
+ Object::Dictionary(dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Contents" => Object::string_literal("direct"),
+ }),
+ ];
+ // `/Annots` is itself allowed to be either an array or a reference to one.
+ let annots = if annots_indirect {
+ Object::Reference(doc.add_object(Object::Array(entries)))
+ } else {
+ Object::Array(entries)
+ };
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Annots" => annots,
+ });
+ (doc, page_id)
+}
+
+fn contents_of(doc: &Document, page_id: lopdf::ObjectId) -> Vec<String> {
+ doc.get_page_annotations(page_id)
+ .unwrap()
+ .iter()
+ .map(|a| String::from_utf8_lossy(a.get(b"Contents").unwrap().as_str().unwrap()).into_owned())
+ .collect()
+}
+
+/// An entry of `/Annots` may be the annotation dictionary itself rather than
+/// a reference to one — ISO 32000-1, 12.5.2 requires an indirect object only
+/// for an annotation that carries a `/Popup` or is an `/IRT` target. Direct
+/// dictionaries used to be dropped without a word, so a page could report
+/// fewer annotations than it has.
+#[test]
+fn page_annotations_include_direct_dictionaries() {
+ let (doc, page_id) = page_with_mixed_annots(false);
+ assert_eq!(contents_of(&doc, page_id), vec!["referenced", "direct"]);
+}
+
+/// The same, with `/Annots` written as a reference to the array.
+#[test]
+fn page_annotations_include_direct_dictionaries_behind_an_indirect_annots() {
+ let (doc, page_id) = page_with_mixed_annots(true);
+ assert_eq!(contents_of(&doc, page_id), vec!["referenced", "direct"]);
+}
+
+/// A reference that does not resolve costs its own annotation, not the page:
+/// the surviving entries still come back.
+#[test]
+fn page_annotations_skip_a_dangling_reference() {
+ let mut doc = Document::with_version("1.7");
+ let good = doc.add_object(dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Contents" => Object::string_literal("kept"),
+ });
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Annots" => vec![
+ Object::Reference((9999, 0)),
+ Object::Reference(good),
+ Object::Null,
+ ],
+ });
+ assert_eq!(contents_of(&doc, page_id), vec!["kept"]);
+}
+
+/// A page without `/Annots` has no annotations, and that is not an error.
+#[test]
+fn page_annotations_without_annots_is_empty() {
+ let mut doc = Document::with_version("1.7");
+ let page_id = doc.add_object(dictionary! { "Type" => "Page" });
+ assert!(doc.get_page_annotations(page_id).unwrap().is_empty());
+}
+
+#[test]
+fn annotation_count() -> Result<()> {
+ // This test file from the pdfcpu repository,
+ // https://github.com/pdfcpu/pdfcpu/blob/master/pkg/samples/basic/AnnotationDemo.pdf
+ let doc = utils::load_document("assets/AnnotationDemo.pdf")?;
+ assert_eq!(doc.version, "1.7".to_string());
+ assert_eq!(doc.page_iter().count(), 1);
+ assert_eq!(doc.get_page_annotations(doc.page_iter().next().unwrap())?.len(), 33);
+ Ok(())
+}
diff --git a/vendor/lopdf/tests/brotli_decode.rs b/vendor/lopdf/tests/brotli_decode.rs
new file mode 100644
index 000000000..0b1e01af2
--- /dev/null
+++ b/vendor/lopdf/tests/brotli_decode.rs
@@ -0,0 +1,92 @@
+use lopdf::{DecompressError, Dictionary, Document, Error, LoadOptions, Object, Stream};
+
+const PAYLOAD: &[u8] = b"BrotliDecode works across filter layers.";
+const COMPRESSED_PAYLOAD: &[u8] = &[
+ 27, 39, 0, 224, 28, 169, 83, 159, 59, 116, 45, 84, 246, 38, 39, 65, 136, 232, 26, 196, 37, 141, 13, 108, 192, 129,
+ 75, 84, 35, 221, 153, 78, 105, 229, 184, 47, 49, 2, 83, 8, 107, 4, 164,
+];
+const COMPRESSED_ASCII_HEX: &[u8] = &[11, 5, 128, 52, 56, 54, 53, 54, 99, 54, 99, 54, 102, 62, 3];
+const COMPRESSED_XREF: &[u8] = &[
+ 27, 34, 0, 0, 4, 54, 224, 26, 71, 93, 117, 151, 221, 6, 135, 28, 200, 5, 14, 196, 81, 11, 176, 12, 144, 100, 228,
+ 47, 106, 153, 208, 15, 0,
+];
+
+fn brotli_stream(content: &[u8]) -> Stream {
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "BrotliDecode");
+ Stream::new(dict, content.to_vec())
+}
+
+fn brotli_xref_pdf() -> Vec<u8> {
+ let mut pdf = Vec::new();
+ pdf.extend_from_slice(b"%PDF-1.5\n");
+ pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
+ pdf.extend_from_slice(b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>\nendobj\n");
+ let xref_offset = pdf.len();
+ assert_eq!(xref_offset, 184, "compressed xref offsets must match the fixture body");
+ pdf.extend_from_slice(
+ b"4 0 obj\n<< /Type /XRef /Size 5 /Root 1 0 R /W [1 4 2] /Length 33 /Filter /BrotliDecode >>\nstream\n",
+ );
+ pdf.extend_from_slice(COMPRESSED_XREF);
+ pdf.extend_from_slice(b"\nendstream\nendobj\nstartxref\n184\n%%EOF\n");
+ pdf
+}
+
+#[test]
+fn brotli_filter_decodes_and_honors_output_limit() {
+ let stream = brotli_stream(COMPRESSED_PAYLOAD);
+
+ assert_eq!(stream.decompressed_content().unwrap(), PAYLOAD);
+ assert_eq!(stream.decompressed_content_with_limit(PAYLOAD.len()).unwrap(), PAYLOAD);
+ assert!(matches!(
+ stream.decompressed_content_with_limit(PAYLOAD.len() - 1),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) if limit == PAYLOAD.len() - 1
+ ));
+}
+
+#[test]
+fn brotli_filter_is_bounded_before_the_next_filter_layer() {
+ let mut dict = Dictionary::new();
+ dict.set(
+ "Filter",
+ vec![Object::from("BrotliDecode"), Object::from("ASCIIHexDecode")],
+ );
+ let stream = Stream::new(dict, COMPRESSED_ASCII_HEX.to_vec());
+
+ assert_eq!(stream.decompressed_content_with_limit(11).unwrap(), b"Hello");
+ assert!(matches!(
+ stream.decompressed_content_with_limit(5),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit: 5 }))
+ ));
+}
+
+#[test]
+fn brotli_xref_stream_decodes_during_load_with_the_same_limit() {
+ let pdf = brotli_xref_pdf();
+ let document = Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(35)).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+
+ assert!(matches!(
+ Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(34)),
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit: 34 }))
+ ));
+}
+
+#[test]
+fn brotli_filter_ignores_decode_parms() {
+ // Producers do not pair /BrotliDecode with predictors — the PDF
+ // Association's prototype files carry no /DecodeParms on any Brotli
+ // stream (their xref streams store raw W entries) — and pdf.js/pypdf
+ // likewise ignore the parameters. The decompressed bytes must therefore
+ // pass through unmodified even when a /DecodeParms dictionary is present.
+ let mut parms = Dictionary::new();
+ parms.set("Predictor", 12);
+ parms.set("Columns", 4);
+ let mut dict = Dictionary::new();
+ dict.set("Filter", Object::from("BrotliDecode"));
+ dict.set("DecodeParms", Object::Dictionary(parms));
+ let stream = Stream::new(dict, COMPRESSED_PAYLOAD.to_vec());
+
+ assert_eq!(stream.decompressed_content().unwrap(), PAYLOAD);
+}
diff --git a/vendor/lopdf/tests/catalog_compression_integration_test.rs b/vendor/lopdf/tests/catalog_compression_integration_test.rs
new file mode 100644
index 000000000..19bc23751
--- /dev/null
+++ b/vendor/lopdf/tests/catalog_compression_integration_test.rs
@@ -0,0 +1,88 @@
+use lopdf::{Document, Object, SaveOptions, dictionary};
+
+#[test]
+fn test_catalog_included_in_object_stream_output() {
+ // Create a simple PDF
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Integration Test PDF",
+ "Author" => "lopdf test suite",
+ });
+
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+
+ // Save with object streams
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .build();
+
+ let mut output = Vec::new();
+ doc.save_with_options(&mut output, options).unwrap();
+
+ // Parse the output to verify catalog is in object stream
+ let saved_doc = Document::load_mem(&output).unwrap();
+
+ // Count object streams
+ let obj_stream_count = saved_doc
+ .objects
+ .iter()
+ .filter(|(_, obj)| {
+ if let Object::Stream(s) = obj {
+ s.dict.get(b"Type").ok() == Some(&Object::Name(b"ObjStm".to_vec()))
+ } else {
+ false
+ }
+ })
+ .count();
+
+ assert!(obj_stream_count > 0, "Should have created object streams");
+
+ // Verify file size reduction by comparing with normal save
+ let mut normal_output = Vec::new();
+ doc.save_to(&mut normal_output).unwrap();
+
+ // For very small PDFs, object streams might increase size due to overhead
+ // The important thing is that the objects are compressed
+ println!("Normal save size: {} bytes", normal_output.len());
+ println!("With object streams: {} bytes", output.len());
+
+ // The key test is that objects are in streams, not the size
+ assert!(obj_stream_count > 0, "Object streams were created");
+
+ // Check that catalog is not an individual object
+ let content = String::from_utf8_lossy(&output);
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Catalog", catalog_id.0)),
+ "Catalog should be in object stream, not as individual object"
+ );
+
+ // Check that info is not an individual object
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Title", info_id.0)),
+ "Info dictionary should be in object stream, not as individual object"
+ );
+}
diff --git a/vendor/lopdf/tests/decompression_bomb.rs b/vendor/lopdf/tests/decompression_bomb.rs
new file mode 100644
index 000000000..cbf92b05c
--- /dev/null
+++ b/vendor/lopdf/tests/decompression_bomb.rs
@@ -0,0 +1,318 @@
+//! Tests for bounded stream decompression (decompression-bomb handling).
+//!
+//! By default `Stream::decompressed_content` is unbounded, so a small compressed
+//! stream can inflate to an arbitrarily large output (a decompression bomb).
+//! These tests cover both the unbounded behavior and the bounded API
+//! (`decompressed_content_with_limit`, `decompress_to_writer`, and
+//! `LoadOptions::max_decompressed_size`) that rejects oversized output,
+//! including nested filters and streams decoded during `Document::load`.
+//!
+//! Bombs are built by streaming zeros through the compressor, so the test
+//! process itself never allocates the full (large) plaintext.
+
+use flate2::Compression;
+use flate2::write::ZlibEncoder;
+use std::io::Write;
+
+use lopdf::{DecompressError, Dictionary, Document, Error, LoadOptions, Object, ObjectId, ObjectStream, Stream};
+
+const MIB: usize = 1024 * 1024;
+
+/// A zlib stream that decodes to `target` zero-bytes, built without ever holding
+/// `target` bytes in memory at once.
+fn flate_bomb(target: usize) -> Vec<u8> {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ let zeros = [0u8; 64 * 1024];
+ let mut remaining = target;
+ while remaining > 0 {
+ let n = remaining.min(zeros.len());
+ encoder.write_all(&zeros[..n]).unwrap();
+ remaining -= n;
+ }
+ encoder.finish().unwrap()
+}
+
+/// Compress arbitrary bytes with zlib (always emits a valid stream).
+fn zlib_compress(data: &[u8]) -> Vec<u8> {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
+ encoder.write_all(data).unwrap();
+ encoder.finish().unwrap()
+}
+
+fn flate_stream(content: Vec<u8>) -> Stream {
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "FlateDecode");
+ Stream::new(dict, content)
+}
+
+/// Assert a result is the memory-limit error for `expected_limit`, without ever
+/// `Debug`-printing a multi-megabyte success value.
+fn assert_limit_err(result: lopdf::Result<Vec<u8>>, expected_limit: usize) {
+ match result.map(|v| v.len()) {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, expected_limit, "error reported the wrong limit");
+ }
+ Ok(n) => panic!("expected MemoryLimitExceeded, but decompressed {n} bytes"),
+ Err(other) => panic!("expected MemoryLimitExceeded, got {other:?}"),
+ }
+}
+
+/// A single `FlateDecode` stream inflates ~32 KiB of input to 32 MiB of output
+/// (~1000x) with no cap — the library materializes the whole thing.
+#[test]
+fn single_filter_bomb_expands_without_limit() {
+ let bomb = flate_stream(flate_bomb(32 * MIB));
+ assert!(
+ bomb.content.len() < 128 * 1024,
+ "input should be tiny: {} bytes",
+ bomb.content.len()
+ );
+
+ let output = bomb.decompressed_content().expect("decodes");
+ assert_eq!(output.len(), 32 * MIB, "the full output was materialized with no cap");
+}
+
+/// Chained filters multiply the amplification: under 8 KiB of input expands to
+/// 32 MiB through `[FlateDecode FlateDecode]`. Additional layers reach petabyte
+/// scale.
+#[test]
+fn chained_filter_bomb_expands_without_limit() {
+ let inner = flate_bomb(32 * MIB); // layer 2 decodes this -> 32 MiB
+ let outer = zlib_compress(&inner); // layer 1 decodes to `inner` (tiny)
+
+ let mut dict = Dictionary::new();
+ dict.set("Filter", vec![Object::from("FlateDecode"), Object::from("FlateDecode")]);
+ let stream = Stream::new(dict, outer);
+
+ assert!(
+ stream.content.len() < 8 * 1024,
+ "input should be under 8 KiB: {} bytes",
+ stream.content.len()
+ );
+
+ let output = stream.decompressed_content().expect("decodes");
+ assert_eq!(output.len(), 32 * MIB, "nested filters expanded fully, no cap");
+}
+
+/// With a limit supplied, the same bomb is rejected before the full 32 MiB is
+/// allocated.
+#[test]
+fn flate_bomb_rejected_with_limit() {
+ let bomb = flate_stream(flate_bomb(32 * MIB));
+ assert_limit_err(bomb.decompressed_content_with_limit(4 * MIB), 4 * MIB);
+}
+
+/// A stream comfortably under the limit still decodes correctly.
+#[test]
+fn legit_stream_decompresses_under_limit() {
+ let payload: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
+ let stream = flate_stream(zlib_compress(&payload));
+
+ let output = stream
+ .decompressed_content_with_limit(MIB)
+ .expect("stream under the limit should decode");
+ assert_eq!(output, payload);
+}
+
+/// The same stream passes or fails based on the chosen limit.
+#[test]
+fn custom_limit_is_enforced() {
+ let stream = flate_stream(flate_bomb(2 * MIB));
+
+ // Limit below the output size: rejected.
+ assert_limit_err(stream.decompressed_content_with_limit(MIB), MIB);
+
+ // Limit above the output size: decoded in full.
+ let output = stream
+ .decompressed_content_with_limit(4 * MIB)
+ .expect("2 MiB output fits under a 4 MiB limit");
+ assert_eq!(output.len(), 2 * MIB);
+}
+
+/// Nested filters (`/Filter [FlateDecode FlateDecode]`) amplify per layer. The
+/// limit bounds each layer, so the bomb is rejected at the second layer instead
+/// of expanding.
+#[test]
+fn chained_flate_filters_are_bounded() {
+ let inner = flate_bomb(32 * MIB); // layer 2 decodes this -> 32 MiB
+ let outer = zlib_compress(&inner); // layer 1 decodes to `inner` (tiny)
+
+ let mut dict = Dictionary::new();
+ dict.set("Filter", vec![Object::from("FlateDecode"), Object::from("FlateDecode")]);
+ let stream = Stream::new(dict, outer);
+
+ assert_limit_err(stream.decompressed_content_with_limit(4 * MIB), 4 * MIB);
+}
+
+/// `decompress_to_writer` enforces the same bound and leaves the caller's sink
+/// untouched on rejection.
+#[test]
+fn decompress_to_writer_bounds_output() {
+ let bomb = flate_stream(flate_bomb(32 * MIB));
+
+ let mut sink: Vec<u8> = Vec::new();
+ let result = bomb.decompress_to_writer(&mut sink, 4 * MIB);
+
+ match result {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, 4 * MIB);
+ }
+ other => panic!(
+ "expected MemoryLimitExceeded, got {:?}",
+ other.map(|n| format!("Ok({n})"))
+ ),
+ }
+ assert!(
+ sink.is_empty(),
+ "sink should be untouched on rejection, got {} bytes",
+ sink.len()
+ );
+}
+
+// Object streams and cross-reference streams are decompressed while the document
+// is loaded, so the limit is supplied through `LoadOptions` to reach them.
+
+/// Build a PDF whose cross-reference stream (`/Type /XRef`) is a FlateDecode
+/// bomb. The reference stream is decoded during `Document::load` to build the
+/// xref table.
+fn xref_stream_bomb_pdf(bomb: &[u8]) -> Vec<u8> {
+ let mut pdf = Vec::new();
+ pdf.extend_from_slice(b"%PDF-1.5\n");
+ let obj_offset = pdf.len();
+ pdf.extend_from_slice(b"1 0 obj\n");
+ pdf.extend_from_slice(
+ format!(
+ "<< /Type /XRef /Size 1 /W [1 1 1] /Root 1 0 R /Filter /FlateDecode /Length {} >>\n",
+ bomb.len()
+ )
+ .as_bytes(),
+ );
+ // Framing matches lopdf's parser: `stream<eol><exactly Length bytes><eol>endstream`.
+ pdf.extend_from_slice(b"stream\n");
+ pdf.extend_from_slice(bomb);
+ pdf.extend_from_slice(b"\nendstream\nendobj\n");
+ pdf.extend_from_slice(format!("startxref\n{obj_offset}\n%%EOF").as_bytes());
+ pdf
+}
+
+/// A bomb in the cross-reference stream is rejected during load when
+/// `max_decompressed_size` is set.
+#[test]
+fn load_time_xref_stream_bomb_is_rejected_with_limit() {
+ let pdf = xref_stream_bomb_pdf(&flate_bomb(64 * MIB));
+
+ let result = Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(4 * MIB));
+
+ match result {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, 4 * MIB);
+ }
+ Err(other) => panic!("expected MemoryLimitExceeded during load, got {other:?}"),
+ Ok(_) => panic!("bomb PDF loaded without hitting the decompression limit"),
+ }
+}
+
+// Page content is decompressed on demand by `Document::get_page_content` (and
+// thus `extract_text`), which is unbounded. `get_page_content_with_limit` bounds
+// the whole concatenated page content to a caller-supplied budget.
+
+/// Build a single-page document whose `/Contents` is the given streams, and
+/// return the document plus the page's object id. No page tree / fonts, so this
+/// exercises `get_page_content_with_limit` directly (not the full extract path).
+fn doc_with_page_streams(streams: Vec<Stream>) -> (Document, ObjectId) {
+ let mut doc = Document::with_version("1.5");
+ let content_refs: Vec<Object> = streams.into_iter().map(|s| doc.add_object(s).into()).collect();
+ let mut page = Dictionary::new();
+ page.set("Type", "Page");
+ page.set("Contents", Object::Array(content_refs));
+ let page_id = doc.add_object(page);
+ (doc, page_id)
+}
+
+/// A bomb in a page's content stream is rejected by `get_page_content_with_limit`
+/// before the full output is allocated.
+#[test]
+fn page_content_bomb_is_rejected_with_limit() {
+ let (doc, page_id) = doc_with_page_streams(vec![flate_stream(flate_bomb(32 * MIB))]);
+ assert_limit_err(doc.get_page_content_with_limit(page_id, 4 * MIB), 4 * MIB);
+}
+
+/// A page comfortably under the limit yields exactly the same bytes as the
+/// unbounded `get_page_content` (including the inter-stream `\n` separators).
+#[test]
+fn page_content_under_limit_matches_unbounded() {
+ let (doc, page_id) = doc_with_page_streams(vec![
+ flate_stream(zlib_compress(b"1 0 0 1 50 100 cm")),
+ flate_stream(zlib_compress(b"BT /F1 12 Tf (hi) Tj ET")),
+ ]);
+
+ let bounded = doc
+ .get_page_content_with_limit(page_id, MIB)
+ .expect("small page content should decode under the limit");
+ assert_eq!(bounded, doc.get_page_content(page_id));
+}
+
+/// The limit is a *total-page* budget, not a per-stream one: two streams that are
+/// each individually under the limit but together exceed it are rejected. (A
+/// per-stream bound would have let this through.)
+#[test]
+fn page_content_limit_is_total_across_streams() {
+ let (doc, page_id) = doc_with_page_streams(vec![
+ flate_stream(flate_bomb(3 * MIB)),
+ flate_stream(flate_bomb(3 * MIB)),
+ ]);
+
+ // Each stream (3 MiB) is under 4 MiB, but 3 + 3 > 4, so the page is rejected.
+ assert_limit_err(doc.get_page_content_with_limit(page_id, 4 * MIB), 4 * MIB);
+}
+
+/// A large *uncompressed* (no `/Filter`) content stream is also bounded: the raw
+/// bytes count against the budget, so it can't bypass the guard.
+#[test]
+fn page_content_uncompressed_over_limit_is_rejected() {
+ let raw = Stream::new(Dictionary::new(), vec![b'x'; 2 * MIB]);
+ let (doc, page_id) = doc_with_page_streams(vec![raw]);
+ assert_limit_err(doc.get_page_content_with_limit(page_id, MIB), MIB);
+}
+
+/// When a stream can't be decoded for a reason *other* than the size limit (here
+/// an unimplemented filter), the code falls back to the raw bytes — but that
+/// fallback is still bounded, so oversized raw content is rejected rather than
+/// silently appended.
+#[test]
+fn page_content_raw_fallback_stays_bounded() {
+ let mut dict = Dictionary::new();
+ dict.set("Filter", "DCTDecode"); // not implemented → decode fails with a non-limit error
+ let undecodable = Stream::new(dict, vec![b'x'; 2 * MIB]);
+
+ let (doc, page_id) = doc_with_page_streams(vec![undecodable]);
+ assert_limit_err(doc.get_page_content_with_limit(page_id, MIB), MIB);
+}
+
+/// A zero limit rejects any non-empty page content without panicking (the
+/// `remaining` budget uses `saturating_sub`).
+#[test]
+fn page_content_zero_limit_rejects_nonempty() {
+ let (doc, page_id) = doc_with_page_streams(vec![flate_stream(zlib_compress(b"BT ET"))]);
+ assert_limit_err(doc.get_page_content_with_limit(page_id, 0), 0);
+}
+
+/// An object stream (`/ObjStm`) is decompressed eagerly during load; the bounded
+/// constructor rejects an oversized stream.
+#[test]
+fn object_stream_bomb_is_rejected_with_limit() {
+ let mut dict = Dictionary::new();
+ dict.set("Type", "ObjStm");
+ dict.set("N", 1i64);
+ dict.set("First", 0i64);
+ dict.set("Filter", "FlateDecode");
+ let stream = Stream::new(dict, flate_bomb(64 * MIB));
+
+ match ObjectStream::new_with_limit(&stream, Some(4 * MIB)) {
+ Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
+ assert_eq!(limit, 4 * MIB);
+ }
+ Err(other) => panic!("expected MemoryLimitExceeded, got {other:?}"),
+ Ok(_) => panic!("object stream bomb was not caught"),
+ }
+}
diff --git a/vendor/lopdf/tests/decryption.rs b/vendor/lopdf/tests/decryption.rs
new file mode 100644
index 000000000..146be911f
--- /dev/null
+++ b/vendor/lopdf/tests/decryption.rs
@@ -0,0 +1,1604 @@
+use lopdf::{Document, Object};
+
+#[cfg(not(feature = "async"))]
+use lopdf::LoadOptions;
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_encrypted_pdf_from_assets() {
+ // Test loading the existing encrypted.pdf file
+ let doc = Document::load("assets/encrypted.pdf").unwrap();
+
+ assert!(
+ !doc.is_encrypted(),
+ "Document should not appear encrypted after decryption"
+ );
+ assert!(doc.encryption_state.is_some());
+
+ // Check that we can access the decrypted content
+ let pages = doc.get_pages();
+ assert_eq!(pages.len(), 1, "Should have exactly one page");
+
+ // Try to extract text from the document
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ // The document should be readable even if encrypted with empty password
+ let text = doc.extract_text(&page_numbers).unwrap();
+
+ // Verify we can extract meaningful text
+ assert!(text.contains("USCIS"), "Should contain USCIS text from the form");
+ assert!(text.contains("Form G-1145"), "Should contain form number");
+
+ // Verify we can access objects
+ for i in 1..=10 {
+ // Should be able to access at least the first 10 objects
+ assert!(
+ doc.get_object((i, 0)).is_ok(),
+ "Should be able to access object ({}, 0)",
+ i
+ );
+ }
+
+ // Verify trailer has required entries
+ assert!(doc.trailer.get(b"Root").is_ok(), "Trailer should have Root entry");
+ assert!(
+ doc.trailer.get(b"Encrypt").is_err(),
+ "Encrypt entry should be removed after decryption"
+ );
+ assert!(doc.trailer.get(b"Info").is_ok(), "Trailer should have Info entry");
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_decrypt_pdf_with_empty_password() {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer (required for encryption)
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a simple page structure
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Create content stream
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Hello, Encrypted World!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Save to a temporary file
+ let temp_dir = tempfile::tempdir().unwrap();
+ let unencrypted_path = temp_dir.path().join("test_unencrypted.pdf");
+ doc.save(&unencrypted_path).unwrap();
+
+ // Encrypt the document with empty password
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "",
+ user_password: "",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let encrypted_path = temp_dir.path().join("test_encrypted.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ // Now test loading the encrypted document
+ let loaded_doc = Document::load(&encrypted_path).unwrap();
+
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ // Check that we can access the decrypted content
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 1);
+
+ // Extract text to verify decryption worked
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = loaded_doc.extract_text(&page_numbers).unwrap();
+ assert!(text.contains("Hello, Encrypted World!"));
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+#[ignore] // Object streams with encryption need more work
+fn test_decrypt_pdf_with_object_streams() {
+ // Create a document with object streams
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer
+ let id1 = vec![10u8, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160];
+ let id2 = vec![160u8, 150, 140, 130, 120, 110, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages tree
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference((3, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
+
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference((2, 0)),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference((4, 0))
+ }
+ },
+ "Contents" => Object::Reference((5, 0))
+ };
+ doc.objects.insert((3, 0), Object::Dictionary(page_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert((4, 0), Object::Dictionary(font_dict));
+
+ // Create content stream
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Test with Object Streams!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert((5, 0), Object::Stream(content_stream));
+
+ // Compress document using object streams
+ doc.compress();
+
+ // Encrypt the document
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_encrypted_objstream.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ // Load and verify
+ let loaded_doc = Document::load(&encrypted_path).unwrap();
+ assert!(loaded_doc.is_encrypted());
+
+ // Verify we can access the content
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 1);
+
+ // Extract text to verify decryption worked
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = loaded_doc.extract_text(&page_numbers).unwrap();
+ assert!(text.contains("Test with Object Streams!"));
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+#[ignore] // Raw object extraction needs adjustments for new decryption approach
+fn test_encrypted_pdf_raw_object_extraction() {
+ // This test verifies that the raw object extraction works correctly
+ // for encrypted PDFs, which is crucial for the pdftk-style decryption
+
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID
+ let id1 = vec![99u8; 16];
+ let id2 = vec![88u8; 16];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a minimal document structure
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Add pages tree
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ };
+ doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
+
+ // Add some test objects with different types
+ doc.objects.insert((10, 0), Object::Integer(42));
+ doc.objects.insert(
+ (11, 0),
+ Object::String(b"test string".to_vec(), lopdf::StringFormat::Literal),
+ );
+ doc.objects.insert(
+ (12, 0),
+ Object::Array(vec![Object::Integer(1), Object::Integer(2), Object::Integer(3)]),
+ );
+
+ // Encrypt
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "test",
+ user_password: "",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save and reload
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_raw_extraction.pdf");
+ doc.save(&path).unwrap();
+
+ let loaded_doc = Document::load(&path).unwrap();
+ assert!(loaded_doc.is_encrypted());
+
+ // Verify that all objects were properly decrypted
+ assert_eq!(loaded_doc.get_object((10, 0)).unwrap().as_i64().unwrap(), 42);
+
+ let string_obj = loaded_doc.get_object((11, 0)).unwrap();
+ if let Object::String(bytes, _) = string_obj {
+ assert_eq!(bytes, b"test string");
+ } else {
+ panic!("Expected string object");
+ }
+
+ let array_obj = loaded_doc.get_object((12, 0)).unwrap();
+ if let Object::Array(arr) = array_obj {
+ assert_eq!(arr.len(), 3);
+ assert_eq!(arr[0].as_i64().unwrap(), 1);
+ assert_eq!(arr[1].as_i64().unwrap(), 2);
+ assert_eq!(arr[2].as_i64().unwrap(), 3);
+ } else {
+ panic!("Expected array object");
+ }
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+#[ignore] // Structure preservation test needs adjustments
+fn test_encrypted_pdf_preserves_structure() {
+ // Test that the document structure is preserved after encryption/decryption
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(vec![77u8; 16], lopdf::StringFormat::Literal),
+ Object::String(vec![66u8; 16], lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a complex structure
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0)),
+ "Metadata" => Object::Reference((3, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Pages tree
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference((4, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
+
+ // Metadata stream
+ let metadata = b"<rdf:RDF>test metadata</rdf:RDF>";
+ let metadata_stream = lopdf::Stream::new(
+ lopdf::dictionary! {
+ "Type" => "Metadata",
+ "Subtype" => "XML"
+ },
+ metadata.to_vec(),
+ );
+ doc.objects.insert((3, 0), Object::Stream(metadata_stream));
+
+ // Page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference((2, 0)),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => lopdf::dictionary! {}
+ };
+ doc.objects.insert((4, 0), Object::Dictionary(page_dict));
+
+ // Encrypt
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "complex",
+ user_password: "",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save and reload
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_structure.pdf");
+ doc.save(&path).unwrap();
+
+ let loaded_doc = Document::load(&path).unwrap();
+ assert!(loaded_doc.is_encrypted());
+
+ // Verify structure is preserved
+ let root = loaded_doc.trailer.get(b"Root").unwrap().as_reference().unwrap();
+ let catalog = loaded_doc.get_object(root).unwrap();
+
+ if let Object::Dictionary(dict) = catalog {
+ assert_eq!(dict.get(b"Type").unwrap(), &Object::Name(b"Catalog".to_vec()));
+ assert!(dict.has(b"Pages"));
+ assert!(dict.has(b"Metadata"));
+ } else {
+ panic!("Expected catalog to be a dictionary");
+ }
+
+ // Check metadata stream was decrypted correctly
+ let metadata_obj = loaded_doc.get_object((3, 0)).unwrap();
+ if let Object::Stream(stream) = metadata_obj {
+ assert_eq!(stream.dict.get(b"Type").unwrap(), &Object::Name(b"Metadata".to_vec()));
+ // Note: Content might be compressed, so we just check it exists
+ assert!(!stream.content.is_empty());
+ } else {
+ panic!("Expected metadata to be a stream");
+ }
+}
+
+#[cfg(feature = "async")]
+#[tokio::test]
+async fn test_decrypt_pdf_with_empty_password_async() {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer (required for encryption)
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a simple page structure (similar to sync version)
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Create content stream
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Hello, Async Encrypted World!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Save to a temporary file
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_encrypted_async.pdf");
+
+ // Encrypt the document with empty password
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "",
+ user_password: "",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+ doc.save(&encrypted_path).unwrap();
+
+ // Now test loading the encrypted document asynchronously
+ let loaded_doc = Document::load(&encrypted_path).await.unwrap();
+
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 1);
+
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = loaded_doc.extract_text(&page_numbers).unwrap();
+ assert!(text.contains("Hello, Async Encrypted World!"));
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_correct_password() {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer (required for encryption)
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a simple page structure
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Create content stream
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Password Protected Content!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Encrypt the document with a NON-EMPTY password
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_secret",
+ user_password: "user_secret", // Non-empty password!
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_password_protected.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ // Test 1: Regular load() should fail to decrypt (no objects loaded because empty password doesn't work)
+ let loaded_without_password = Document::load(&encrypted_path).unwrap();
+ assert!(
+ loaded_without_password.is_encrypted(),
+ "Should still appear encrypted when auth fails"
+ );
+
+ // load_with_password() with correct password should work
+ let loaded_with_password = Document::load_with_password(&encrypted_path, "user_secret").unwrap();
+ assert!(
+ !loaded_with_password.is_encrypted(),
+ "Should not appear encrypted after successful decryption"
+ );
+ assert!(loaded_with_password.encryption_state.is_some());
+
+ let pages = loaded_with_password.get_pages();
+ assert_eq!(pages.len(), 1, "Should have exactly one page");
+
+ // Extract text to verify decryption worked
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = loaded_with_password.extract_text(&page_numbers).unwrap();
+ assert!(
+ text.contains("Password Protected Content!"),
+ "Should be able to extract text: {}",
+ text
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_wrong_password() {
+ use lopdf::Error;
+
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Minimal document structure
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ };
+ doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
+
+ // Encrypt with a specific password
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "correct_owner",
+ user_password: "correct_user",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_wrong_password.pdf");
+ doc.save(&path).unwrap();
+
+ // Try to load with wrong password - should fail
+ let result = Document::load_with_password(&path, "wrong_password");
+ assert!(result.is_err(), "Should fail with wrong password");
+
+ if let Err(Error::InvalidPassword) = result {
+ // Good - got the expected error
+ } else {
+ panic!("Expected InvalidPassword error, got: {:?}", result);
+ }
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_empty_password_when_required() {
+ use lopdf::Error;
+
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Minimal document
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![],
+ "Count" => 0
+ };
+ doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
+
+ // Encrypt with NON-empty password
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "secret",
+ user_password: "secret",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_empty_password.pdf");
+ doc.save(&path).unwrap();
+
+ // Try to load with empty password when document requires a real password
+ // This should fail with InvalidPassword
+ let result = Document::load_with_password(&path, "");
+ assert!(result.is_err(), "Should fail when empty password doesn't work");
+
+ if let Err(Error::InvalidPassword) = result {
+ // Good - got the expected error
+ } else {
+ panic!("Expected InvalidPassword error, got: {:?}", result);
+ }
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_mem_with_password() {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a simple page structure
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Memory Loaded!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Encrypt with password
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "mem_owner",
+ user_password: "mem_user",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save to memory buffer
+ let mut buffer = Vec::new();
+ doc.save_to(&mut buffer).unwrap();
+
+ let loaded_doc = Document::load_mem_with_options(&buffer, LoadOptions::with_password("mem_user")).unwrap();
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 1);
+}
+
+#[cfg(feature = "async")]
+#[tokio::test]
+async fn test_load_with_password_async() {
+ // Create a simple PDF document
+ let mut doc = Document::with_version("1.5");
+
+ // Add ID
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create minimal structure
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Async Password Protected!) Tj\nET\n";
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Encrypt
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "async_owner",
+ user_password: "async_user",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_async_password.pdf");
+ doc.save(&path).unwrap();
+
+ let loaded_doc = Document::load_with_password(&path, "async_user").await.unwrap();
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 1);
+}
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_multipage_pdf() {
+ // Create a PDF document with multiple pages
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer (required for encryption)
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a multi-page document
+ let pages_id = doc.new_object_id();
+ let page1_id = doc.new_object_id();
+ let page2_id = doc.new_object_id();
+ let page3_id = doc.new_object_id();
+ let content1_id = doc.new_object_id();
+ let content2_id = doc.new_object_id();
+ let content3_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages tree with 3 pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page1_id), Object::Reference(page2_id), Object::Reference(page3_id)],
+ "Count" => 3
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create page 1
+ let page1_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content1_id)
+ };
+ doc.objects.insert(page1_id, Object::Dictionary(page1_dict));
+
+ // Create page 2
+ let page2_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content2_id)
+ };
+ doc.objects.insert(page2_id, Object::Dictionary(page2_dict));
+
+ // Create page 3
+ let page3_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content3_id)
+ };
+ doc.objects.insert(page3_id, Object::Dictionary(page3_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Create content streams
+ let content1 = b"BT\n/F1 12 Tf\n100 700 Td\n(Page 1 Content!) Tj\nET\n";
+ let content1_stream = lopdf::Stream::new(lopdf::dictionary! {}, content1.to_vec());
+ doc.objects.insert(content1_id, Object::Stream(content1_stream));
+
+ let content2 = b"BT\n/F1 12 Tf\n100 700 Td\n(Page 2 Content!) Tj\nET\n";
+ let content2_stream = lopdf::Stream::new(lopdf::dictionary! {}, content2.to_vec());
+ doc.objects.insert(content2_id, Object::Stream(content2_stream));
+
+ let content3 = b"BT\n/F1 12 Tf\n100 700 Td\n(Page 3 Content!) Tj\nET\n";
+ let content3_stream = lopdf::Stream::new(lopdf::dictionary! {}, content3.to_vec());
+ doc.objects.insert(content3_id, Object::Stream(content3_stream));
+
+ // Encrypt the document with a NON-EMPTY password
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_secret",
+ user_password: "user_secret", // Non-empty password!
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_multipage_encrypted.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ // Get file size for debugging
+ let file_metadata = std::fs::metadata(&encrypted_path).unwrap();
+ let original_size = file_metadata.len();
+ println!("Encrypted PDF size: {} bytes", original_size);
+
+ let loaded_doc = Document::load_with_password(&encrypted_path, "user_secret").unwrap();
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ let pages = loaded_doc.get_pages();
+ assert_eq!(pages.len(), 3, "Should have exactly 3 pages, but got {}", pages.len());
+
+ let object_count = loaded_doc.objects.len();
+ println!("Loaded document has {} objects", object_count);
+
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = loaded_doc.extract_text(&page_numbers).unwrap();
+ println!("Extracted text: {}", text);
+
+ assert!(
+ text.contains("Page 1 Content!"),
+ "Should contain Page 1 content: {}",
+ text
+ );
+ assert!(
+ text.contains("Page 2 Content!"),
+ "Should contain Page 2 content: {}",
+ text
+ );
+ assert!(
+ text.contains("Page 3 Content!"),
+ "Should contain Page 3 content: {}",
+ text
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_with_compressed_streams() {
+ // Create a PDF document with compressed streams
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer (required for encryption)
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let pages_id = doc.new_object_id();
+ let page1_id = doc.new_object_id();
+ let page2_id = doc.new_object_id();
+ let content1_id = doc.new_object_id();
+ let content2_id = doc.new_object_id();
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages tree with 2 pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page1_id), Object::Reference(page2_id)],
+ "Count" => 2
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create page 1
+ let page1_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content1_id)
+ };
+ doc.objects.insert(page1_id, Object::Dictionary(page1_dict));
+
+ // Create page 2
+ let page2_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(content2_id)
+ };
+ doc.objects.insert(page2_id, Object::Dictionary(page2_dict));
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Create content streams - Note: these will be compressed by the Stream
+ let content1 = b"BT\n/F1 12 Tf\n100 700 Td\n(Compressed Page 1!) Tj\nET\n";
+ let mut content1_stream = lopdf::Stream::new(lopdf::dictionary! { "Filter" => "FlateDecode" }, content1.to_vec());
+ content1_stream.compress().unwrap();
+ doc.objects.insert(content1_id, Object::Stream(content1_stream));
+
+ let content2 = b"BT\n/F1 12 Tf\n100 700 Td\n(Compressed Page 2!) Tj\nET\n";
+ let mut content2_stream = lopdf::Stream::new(lopdf::dictionary! { "Filter" => "FlateDecode" }, content2.to_vec());
+ content2_stream.compress().unwrap();
+ doc.objects.insert(content2_id, Object::Stream(content2_stream));
+
+ // Encrypt the document
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_secret",
+ user_password: "user_secret",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_compressed_encrypted.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ // Get file size for debugging
+ let file_metadata = std::fs::metadata(&encrypted_path).unwrap();
+ println!("Compressed encrypted PDF size: {} bytes", file_metadata.len());
+
+ let loaded_doc = Document::load_with_password(&encrypted_path, "user_secret").unwrap();
+ assert!(
+ !loaded_doc.is_encrypted(),
+ "Should not appear encrypted after decryption"
+ );
+ assert!(loaded_doc.encryption_state.is_some());
+
+ let pages = loaded_doc.get_pages();
+ println!("Loaded {} pages", pages.len());
+ assert_eq!(pages.len(), 2, "Should have exactly 2 pages, but got {}", pages.len());
+
+ let object_count = loaded_doc.objects.len();
+ println!("Loaded document has {} objects", object_count);
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_with_password_stream_with_endobj_bytes() {
+ // Test with binary content that contains "endobj" substring
+ let mut doc = Document::with_version("1.5");
+
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let pages_id = doc.new_object_id();
+ let page_id = doc.new_object_id();
+ let content_id = doc.new_object_id();
+ let second_obj_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages tree
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Contents" => Object::Reference(content_id)
+ };
+ doc.objects.insert(page_id, Object::Dictionary(page_dict));
+
+ // Create a content stream that contains "endobj" in its binary content
+ // This simulates what can happen with compressed/binary streams
+ let mut content = b"BT\n/F1 12 Tf\n100 700 Td\n(Test) Tj\nET\n".to_vec();
+ // Add "endobj" bytes in the stream content
+ content.extend_from_slice(b"endobj fake marker");
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content);
+ doc.objects.insert(content_id, Object::Stream(content_stream));
+
+ // Add another object that should be loaded after the stream
+ doc.objects.insert(second_obj_id, Object::Integer(42));
+
+ // Encrypt the document
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_secret",
+ user_password: "user_secret",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_stream_with_endobj.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ println!("PDF with endobj in stream saved to: {}", encrypted_path.display());
+
+ // Load with password
+ let loaded_doc = Document::load_with_password(&encrypted_path, "user_secret").unwrap();
+
+ // Verify all objects were loaded
+ let object_count = loaded_doc.objects.len();
+ println!("Loaded {} objects", object_count);
+
+ // The second object should be loaded
+ assert!(
+ loaded_doc.get_object(second_obj_id).is_ok(),
+ "Second object should be loaded"
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_load_encrypted_pdf_with_object_streams() {
+ // Load the encrypted.pdf from assets
+ let doc = Document::load("assets/encrypted.pdf").unwrap();
+
+ println!("Document version: {}", doc.version);
+ println!("Number of objects: {}", doc.objects.len());
+
+ // Check if document has object streams
+ let mut has_obj_stream = false;
+ for (id, obj) in &doc.objects {
+ if let Object::Stream(stream) = obj
+ && stream.dict.has_type(b"ObjStm")
+ {
+ has_obj_stream = true;
+ println!("Found object stream: {:?}", id);
+ }
+ }
+ println!("Has object streams: {}", has_obj_stream);
+
+ // Check the pages
+ let pages = doc.get_pages();
+ println!("Number of pages: {}", pages.len());
+
+ // Try to extract text
+ let page_numbers: Vec<u32> = pages.keys().cloned().collect();
+ let text = doc.extract_text(&page_numbers).unwrap();
+ println!("Extracted {} characters of text", text.len());
+
+ assert!(!pages.is_empty(), "Should have at least one page");
+
+ // Now save and reload to verify round-trip
+ let temp_dir = tempfile::tempdir().unwrap();
+ let saved_path = temp_dir.path().join("encrypted_resaved.pdf");
+
+ let mut doc_clone = doc.clone();
+ doc_clone.save(&saved_path).unwrap();
+
+ let file_size = std::fs::metadata(&saved_path).unwrap().len();
+ println!("Saved file size: {} bytes", file_size);
+
+ // Verify the saved file can be loaded and has the same content
+ let reloaded = Document::load(&saved_path).unwrap();
+ let reloaded_pages = reloaded.get_pages();
+ println!(
+ "Reloaded document has {} pages and {} objects",
+ reloaded_pages.len(),
+ reloaded.objects.len()
+ );
+
+ assert_eq!(
+ pages.len(),
+ reloaded_pages.len(),
+ "Should have same number of pages after round-trip"
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_encrypt_decrypt_multipage_roundtrip() {
+ // Create a PDF document with multiple pages
+ let mut doc = Document::with_version("1.5");
+
+ // Add an ID to the trailer
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1.clone(), lopdf::StringFormat::Literal),
+ Object::String(id2.clone(), lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ // Create a multi-page document with 5 pages
+ let pages_id = doc.new_object_id();
+ let mut page_ids = Vec::new();
+ let mut content_ids = Vec::new();
+
+ for _ in 0..5 {
+ page_ids.push(doc.new_object_id());
+ content_ids.push(doc.new_object_id());
+ }
+
+ let font_id = doc.new_object_id();
+ let resources_id = doc.new_object_id();
+
+ // Create catalog
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id)
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ // Create pages tree with 5 pages
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => page_ids.iter().map(|id| Object::Reference(*id)).collect::<Vec<_>>(),
+ "Count" => 5
+ };
+ doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
+
+ // Create resources
+ let resources_dict = lopdf::dictionary! {
+ "Font" => lopdf::dictionary! {
+ "F1" => Object::Reference(font_id)
+ }
+ };
+ doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
+
+ // Create pages and content
+ for (i, (page_id, content_id)) in page_ids.iter().zip(content_ids.iter()).enumerate() {
+ // Create page
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
+ "Resources" => Object::Reference(resources_id),
+ "Contents" => Object::Reference(*content_id)
+ };
+ doc.objects.insert(*page_id, Object::Dictionary(page_dict));
+
+ // Create content stream
+ let content = format!(
+ "BT\n/F1 12 Tf\n100 700 Td\n(Page {} Content - Test String!) Tj\nET\n",
+ i + 1
+ );
+ let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.into_bytes());
+ doc.objects.insert(*content_id, Object::Stream(content_stream));
+ }
+
+ // Create font
+ let font_dict = lopdf::dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ };
+ doc.objects.insert(font_id, Object::Dictionary(font_dict));
+
+ // Save unencrypted version first for size comparison
+ let temp_dir = tempfile::tempdir().unwrap();
+ let unencrypted_path = temp_dir.path().join("multipage_unencrypted.pdf");
+ doc.save(&unencrypted_path).unwrap();
+ let unencrypted_size = std::fs::metadata(&unencrypted_path).unwrap().len();
+ println!("Unencrypted PDF size: {} bytes", unencrypted_size);
+
+ // Encrypt the document with a NON-EMPTY password
+ let permissions = lopdf::Permissions::all();
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_password",
+ user_password: "test_password",
+ key_length: 128,
+ permissions,
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // Save encrypted document
+ let encrypted_path = temp_dir.path().join("multipage_encrypted.pdf");
+ doc.save(&encrypted_path).unwrap();
+ let encrypted_size = std::fs::metadata(&encrypted_path).unwrap().len();
+ println!("Encrypted PDF size: {} bytes", encrypted_size);
+
+ // Now load the encrypted PDF with password
+ let loaded_doc = Document::load_with_password(&encrypted_path, "test_password").unwrap();
+
+ let loaded_pages = loaded_doc.get_pages();
+ let loaded_objects = loaded_doc.objects.len();
+ println!(
+ "Loaded document: {} pages, {} objects",
+ loaded_pages.len(),
+ loaded_objects
+ );
+
+ // Verify all 5 pages are loaded
+ assert_eq!(loaded_pages.len(), 5, "Should have 5 pages, got {}", loaded_pages.len());
+
+ // Extract text from all pages
+ let page_numbers: Vec<u32> = loaded_pages.keys().cloned().collect();
+ let text = loaded_doc.extract_text(&page_numbers).unwrap();
+ println!("Extracted text length: {} chars", text.len());
+
+ // Verify content from each page
+ for i in 1..=5 {
+ let expected = format!("Page {}", i);
+ assert!(
+ text.contains(&expected),
+ "Should contain text from page {}: text = '{}'",
+ i,
+ text
+ );
+ }
+
+ // Re-save the loaded document (this is the user's scenario)
+ let resaved_path = temp_dir.path().join("multipage_resaved.pdf");
+ let mut loaded_doc_mut = loaded_doc.clone();
+ loaded_doc_mut.save(&resaved_path).unwrap();
+ let resaved_size = std::fs::metadata(&resaved_path).unwrap().len();
+ println!("Re-saved PDF size: {} bytes", resaved_size);
+
+ // The re-saved file should be similar size (within reasonable bounds)
+ // It shouldn't be drastically smaller like the user's issue (468 bytes vs 197KB)
+ assert!(
+ resaved_size > unencrypted_size / 2,
+ "Re-saved file is too small! Got {} bytes, expected at least {} bytes",
+ resaved_size,
+ unencrypted_size / 2
+ );
+
+ // Load the re-saved document and verify pages
+ let reloaded = Document::load(&resaved_path).unwrap();
+ let reloaded_pages = reloaded.get_pages();
+ println!(
+ "Re-loaded document: {} pages, {} objects",
+ reloaded_pages.len(),
+ reloaded.objects.len()
+ );
+
+ assert_eq!(
+ reloaded_pages.len(),
+ 5,
+ "Re-loaded should have 5 pages, got {}",
+ reloaded_pages.len()
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_was_encrypted_method() {
+ // Test 1: Unencrypted document
+ let mut doc = Document::with_version("1.5");
+ let catalog_dict = lopdf::dictionary! { "Type" => "Catalog" };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ assert!(!doc.is_encrypted(), "Unencrypted doc should not be encrypted");
+ assert!(!doc.was_encrypted(), "Unencrypted doc was not originally encrypted");
+
+ // Test 2: Create and load encrypted document
+ let id1 = vec![1u8; 16];
+ let id2 = vec![2u8; 16];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id1, lopdf::StringFormat::Literal),
+ Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ // After encryption, before saving
+ assert!(doc.is_encrypted(), "Should be encrypted after encrypt()");
+
+ // Save and reload with password
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_was_encrypted.pdf");
+ doc.save(&path).unwrap();
+
+ let loaded = Document::load_with_password(&path, "user").unwrap();
+
+ // After loading with correct password: decrypted but was_encrypted is true
+ assert!(!loaded.is_encrypted(), "Should not appear encrypted after decryption");
+ assert!(loaded.was_encrypted(), "Should remember it was originally encrypted");
+
+ // Test 3: Load encrypted doc without correct password (empty doesn't work)
+ let loaded_locked = Document::load(&path).unwrap();
+ assert!(
+ loaded_locked.is_encrypted(),
+ "Should still appear encrypted without password"
+ );
+ assert!(
+ !loaded_locked.was_encrypted(),
+ "encryption_state not set when auth failed"
+ );
+}
diff --git a/vendor/lopdf/tests/document_load_performance.rs b/vendor/lopdf/tests/document_load_performance.rs
new file mode 100644
index 000000000..cc0c09e3b
--- /dev/null
+++ b/vendor/lopdf/tests/document_load_performance.rs
@@ -0,0 +1,40 @@
+#[cfg(not(feature = "async"))]
+use lopdf::Document;
+#[cfg(not(feature = "async"))]
+use std::time::Instant;
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn page_count_meta_data_performance_test() {
+ let document_path = "assets/test.pdf";
+ let start_time = Instant::now();
+ let doc = Document::load_metadata(document_path).expect("Failed to load document");
+ let result = doc.page_count;
+ let elapsed_time = start_time.elapsed();
+ println!("--- Meta Page Count Stats ---");
+ println!("Page count: {} in {:.2}s", result, elapsed_time.as_secs_f64());
+ assert_eq!(result, 100);
+ assert!(
+ elapsed_time.as_millis() < 100,
+ "Expected load in <100ms, got {}ms",
+ elapsed_time.as_millis()
+ );
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn page_count_performance_test() {
+ let document_path = "assets/test.pdf";
+ let start_time = Instant::now();
+ let doc = Document::load(document_path).expect("Failed to load document");
+ let result = doc.get_pages().len();
+ let elapsed_time = start_time.elapsed();
+ println!("--- Page Count Stats ---");
+ println!("Page count: {} in {:.2}s", result, elapsed_time.as_secs_f64());
+ assert_eq!(result, 100);
+ assert!(
+ elapsed_time.as_millis() < 100,
+ "Expected load in <100ms, got {}ms",
+ elapsed_time.as_millis()
+ );
+}
diff --git a/vendor/lopdf/tests/encrypted_object_stream_test.rs b/vendor/lopdf/tests/encrypted_object_stream_test.rs
new file mode 100644
index 000000000..5ffd3c2fe
--- /dev/null
+++ b/vendor/lopdf/tests/encrypted_object_stream_test.rs
@@ -0,0 +1,185 @@
+//! Saving an encrypted document with object streams enabled.
+//!
+//! Object streams are assembled while serializing, long after `Document::encrypt`
+//! has encrypted every object and dropped the file encryption key, so the writer
+//! has nothing left to encrypt one with.
+//! See https://github.com/J-F-Liu/lopdf/issues/479.
+
+#![cfg(not(feature = "async"))]
+
+use lopdf::{
+ Document, EncryptionState, EncryptionVersion, LoadOptions, Object, Permissions, SaveOptions, Stream, StringFormat,
+ dictionary,
+};
+
+/// Build a one page document carrying a string we can check after a round trip.
+fn sample_document() -> Document {
+ let mut doc = Document::with_version("1.7");
+
+ let pages_id = doc.new_object_id();
+ let content_id = doc.add_object(Stream::new(dictionary! {}, b"BT ET".to_vec()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => Object::Reference(content_id),
+ });
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1,
+ }),
+ );
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id),
+ });
+ let info_id = doc.add_object(dictionary! {
+ "Title" => Object::String(b"lopdf 479".to_vec(), StringFormat::Literal),
+ });
+
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+ doc.trailer.set("Info", Object::Reference(info_id));
+ let id = vec![0x42u8; 16];
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(id.clone(), StringFormat::Literal),
+ Object::String(id, StringFormat::Literal),
+ ]),
+ );
+
+ doc
+}
+
+/// AES-128, the setup from the issue report.
+fn encrypt_aes128(doc: &mut Document) {
+ use std::collections::BTreeMap;
+ use std::sync::Arc;
+
+ let crypt_filter: Arc<dyn lopdf::encryption::crypt_filters::CryptFilter> =
+ Arc::new(lopdf::encryption::crypt_filters::Aes128CryptFilter);
+ let version = EncryptionVersion::V4 {
+ document: doc,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "",
+ permissions: Permissions::PRINTABLE,
+ };
+ let state = EncryptionState::try_from(version).unwrap();
+ doc.encrypt(&state).unwrap();
+}
+
+/// RC4-128, to show the problem is not specific to the AES crypt filters.
+fn encrypt_rc4_128(doc: &mut Document) {
+ let version = EncryptionVersion::V2 {
+ document: doc,
+ owner_password: "owner",
+ user_password: "",
+ key_length: 128,
+ permissions: Permissions::PRINTABLE,
+ };
+ let state = EncryptionState::try_from(version).unwrap();
+ doc.encrypt(&state).unwrap();
+}
+
+fn contains(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|window| window == needle)
+}
+
+/// Assert the saved bytes are a readable encrypted PDF.
+fn assert_round_trips(buffer: &[u8], label: &str) {
+ let doc = Document::load_mem_with_options(buffer, LoadOptions::with_password("owner"))
+ .unwrap_or_else(|err| panic!("{label}: reloading the saved document failed: {err:?}"));
+
+ assert!(doc.was_encrypted(), "{label}: document should have been encrypted");
+
+ let pages = doc.get_pages();
+ assert_eq!(pages.len(), 1, "{label}: expected exactly one page");
+
+ // Before the fix this came back as the raw ciphertext of the title: the object
+ // holding it was packed into an object stream, so the reader decrypts the stream
+ // as a whole and correctly leaves the strings inside it alone, but `encrypt` had
+ // already encrypted them individually.
+ let title = doc
+ .trailer
+ .get(b"Info")
+ .and_then(Object::as_reference)
+ .and_then(|id| doc.get_dictionary(id))
+ .and_then(|dict| dict.get(b"Title"))
+ .and_then(Object::as_str)
+ .unwrap_or_else(|err| panic!("{label}: /Title is unreadable: {err:?}"));
+ assert_eq!(title, b"lopdf 479", "{label}: /Title did not survive the round trip");
+
+ let page_id = *pages.get(&1).unwrap();
+ let content = doc.get_page_content(page_id);
+ assert_eq!(
+ content.trim_ascii_end(),
+ b"BT ET",
+ "{label}: page content did not survive the round trip"
+ );
+}
+
+#[test]
+fn save_modern_keeps_encrypted_documents_readable() {
+ let mut doc = sample_document();
+ encrypt_aes128(&mut doc);
+
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ assert_round_trips(&buffer, "save_modern");
+}
+
+#[test]
+fn save_with_object_streams_keeps_encrypted_rc4_documents_readable() {
+ let mut doc = sample_document();
+ encrypt_rc4_128(&mut doc);
+
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(false)
+ .build();
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ assert_round_trips(&buffer, "save_with_options");
+}
+
+#[test]
+fn save_modern_writes_no_object_stream_when_encrypted() {
+ let mut doc = sample_document();
+ encrypt_aes128(&mut doc);
+
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ assert!(
+ !contains(&buffer, b"/ObjStm"),
+ "an encrypted document must not be packed into an object stream the writer cannot encrypt"
+ );
+ // The fallback drops object streams only. Cross-reference streams are never
+ // encrypted, so `save_modern` still gets the modern cross-reference section.
+ assert!(
+ contains(&buffer, b"/XRef"),
+ "the requested cross-reference stream should still be written"
+ );
+}
+
+#[test]
+fn save_modern_still_uses_object_streams_when_not_encrypted() {
+ let mut doc = sample_document();
+
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ assert!(
+ contains(&buffer, b"/ObjStm"),
+ "an unencrypted document should still be packed into object streams"
+ );
+}
diff --git a/vendor/lopdf/tests/extract_test.rs b/vendor/lopdf/tests/extract_test.rs
new file mode 100644
index 000000000..e4ccf2244
--- /dev/null
+++ b/vendor/lopdf/tests/extract_test.rs
@@ -0,0 +1,211 @@
+use lopdf::content::{Content, Operation};
+use lopdf::{Document, Object, Stream, StringFormat, dictionary};
+
+// These ToUnicode CMaps are extracted from a real PDF which I have that have these
+// `0 beginbfrange ... endbfrange` sections. Historically (i.e version 0.38.0) this could trigger parse
+// failures and break text extraction.
+const FONT1_TOUNICODE: &str = r#"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo
+<< /Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName /Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+0 beginbfrange
+endbfrange
+2 beginbfchar
+<0003> <0020>
+<0006> <0023>
+endbfchar
+3 beginbfrange
+<0008> <0009> <0025>
+<000b> <000c> <0028>
+<000f> <0016> <002c>
+endbfrange
+3 beginbfchar
+<001a> <0037>
+<001d> <003a>
+<0022> <003f>
+endbfchar
+3 beginbfrange
+<0024> <002a> <0041>
+<002c> <002d> <0049>
+<002f> <0031> <004c>
+endbfrange
+1 beginbfchar
+<0033> <0050>
+endbfchar
+1 beginbfrange
+<0035> <0038> <0052>
+endbfrange
+2 beginbfchar
+<003a> <0057>
+<003c> <0059>
+endbfchar
+2 beginbfrange
+<0044> <004c> <0061>
+<004e> <005d> <006b>
+endbfrange
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end
+"#;
+
+const FONT2_TOUNICODE: &str = r#"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo
+<< /Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName /Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+0 beginbfrange
+endbfrange
+2 beginbfchar
+<0003> <0020>
+<0007> <0024>
+endbfchar
+2 beginbfrange
+<000a> <000c> <0027>
+<000e> <0019> <002b>
+endbfrange
+1 beginbfchar
+<001b> <0038>
+endbfchar
+5 beginbfrange
+<001d> <001f> <003a>
+<0021> <0022> <003e>
+<0024> <002c> <0041>
+<002e> <003b> <004b>
+<0044> <005d> <0061>
+endbfrange
+2 beginbfchar
+<0061> <007e>
+<00bc> <20ac>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end
+"#;
+
+fn build_doc_with_tounicode(tounicode: &str, encoded_text: Vec<u8>) -> Document {
+ let mut doc = Document::with_version("1.5");
+
+ let pages_id = doc.new_object_id();
+
+ let tounicode_bytes = tounicode.as_bytes().to_vec();
+ let tounicode_stream_id = doc.add_object(Stream::new(
+ dictionary! { "Length" => tounicode_bytes.len() as i64 },
+ tounicode_bytes,
+ ));
+
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type0",
+ "BaseFont" => "DummyFont",
+ "Encoding" => "Identity-H",
+ "ToUnicode" => Object::Reference(tounicode_stream_id),
+ });
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ Operation::new("Td", vec![50.into(), 700.into()]),
+ Operation::new("Tj", vec![Object::String(encoded_text, StringFormat::Hexadecimal)]),
+ Operation::new("ET", vec![]),
+ ],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Resources" => resources_id,
+ "Contents" => content_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ doc
+}
+
+#[test]
+fn extract_text_does_not_error_with_empty_bfrange_font2() {
+ // Sequence of 2-byte character codes (Identity-H):
+ // <0003> -> U+0020 (space)
+ // <0007> -> U+0024 ($)
+ // <000a> -> U+0027 (') via bfrange
+ // <001b> -> U+0038 (8) via bfchar
+ // <0061> -> U+007E (~) via bfchar
+ // <00bc> -> U+20AC (€) via bfchar
+ let encoded_text = vec![
+ 0x00, 0x03, // space
+ 0x00, 0x07, // $
+ 0x00, 0x0a, // '
+ 0x00, 0x1b, // 8
+ 0x00, 0x61, // ~
+ 0x00, 0xbc, // €
+ ];
+
+ let doc = build_doc_with_tounicode(FONT2_TOUNICODE, encoded_text);
+
+ let text = doc.extract_text(&[1]).expect("extract_text should not error");
+ assert_eq!(text.trim_end(), " $'8~€");
+}
+
+#[test]
+fn extract_text_does_not_error_with_empty_bfrange_font1() {
+ // Exercise both bfchar and bfrange sections, and include the initial empty bfrange section.
+ // <0003> -> space
+ // <0006> -> #
+ // <0008> -> % via bfrange (<0008> <0009> <0025>)
+ // <001a> -> 7 via bfchar
+ // <0044> -> a via bfrange (<0044> <004c> <0061>)
+ let encoded_text = vec![
+ 0x00, 0x03, // space
+ 0x00, 0x06, // #
+ 0x00, 0x08, // %
+ 0x00, 0x1a, // 7
+ 0x00, 0x44, // a
+ ];
+
+ let doc = build_doc_with_tounicode(FONT1_TOUNICODE, encoded_text);
+
+ let text = doc.extract_text(&[1]).expect("extract_text should not error");
+ assert_eq!(text.trim_end(), " #%7a");
+}
diff --git a/vendor/lopdf/tests/font_test.rs b/vendor/lopdf/tests/font_test.rs
new file mode 100644
index 000000000..6dc49af8e
--- /dev/null
+++ b/vendor/lopdf/tests/font_test.rs
@@ -0,0 +1,35 @@
+#[cfg(feature = "font_embedding")]
+#[test]
+fn test_font_data_creation() {
+ // Load a sample TTF font file from the test resources
+ let font_file = std::fs::read("./assets/fonts/Montserrat-Regular.ttf");
+
+ // Ensure the font file was read successfully
+ assert!(font_file.is_ok(), "Failed to read font file");
+
+ // Unwrap the result to get the font file bytes
+ let font_file = font_file.unwrap();
+ let mut font_data = lopdf::FontData::new(&font_file, "Montserrat-Regular".to_string());
+
+ // Create a new FontData instance
+ font_data
+ .set_font_bbox((0, -200, 1000, 800))
+ .set_italic_angle(10)
+ .set_ascent(800)
+ .set_descent(-200)
+ .set_cap_height(700)
+ .set_stem_v(100)
+ .set_flags(4)
+ .set_encoding("WinAnsiEncoding".to_string());
+
+ // Verify the properties of the FontData instance
+ assert_eq!(font_data.font_bbox, (0, -200, 1000, 800));
+ assert_eq!(font_data.italic_angle, 10);
+ assert_eq!(font_data.ascent, 800);
+ assert_eq!(font_data.descent, -200);
+ assert_eq!(font_data.cap_height, 700);
+ assert_eq!(font_data.stem_v, 100);
+ assert_eq!(font_data.flags, 4);
+ assert_eq!(font_data.encoding, "WinAnsiEncoding");
+ assert!(!font_data.bytes().is_empty(), "Font data should not be empty");
+}
diff --git a/vendor/lopdf/tests/incremental_document.rs b/vendor/lopdf/tests/incremental_document.rs
new file mode 100644
index 000000000..5f1196a62
--- /dev/null
+++ b/vendor/lopdf/tests/incremental_document.rs
@@ -0,0 +1,495 @@
+use lopdf::encryption::crypt_filters::{Aes128CryptFilter, Aes256CryptFilter, CryptFilter};
+use lopdf::xref::XrefType;
+use lopdf::{
+ Document, EncryptionState, EncryptionVersion, IncrementalDocument, LoadOptions, Object, Permissions, Result,
+ Stream, dictionary,
+};
+use std::collections::BTreeMap;
+use std::fs;
+use std::io;
+use std::sync::Arc;
+use tempfile::tempdir;
+
+mod utils;
+
+#[test]
+fn load_incremental_file_as_linear_file() -> Result<()> {
+ let doc = utils::load_document("assets/Incremental.pdf")?;
+ assert_eq!(doc.version, "1.5".to_string());
+
+ Ok(())
+}
+
+#[test]
+fn load_incremental_file() -> Result<()> {
+ let mut doc = utils::load_incremental_document("assets/Incremental.pdf")?;
+ assert_eq!(doc.get_prev_documents().version, "1.5".to_string());
+
+ // Create temporary folder to store file.
+ let temp_dir = tempdir()?;
+ let file_path = temp_dir.path().join("test_4_incremental.pdf");
+ doc.save(file_path)?;
+
+ Ok(())
+}
+
+/// An incremental update must not open with a file header. ISO 32000-1,
+/// 7.5.6 defines it as the original bytes followed by the changed objects, a
+/// cross-reference section and a trailer: the header belongs to the *file*,
+/// and the previous revision already carries it.
+///
+/// Two things went wrong with the second `%PDF-x.y`. A file that appears to
+/// start another document halfway through misleads anything that locates a
+/// PDF by scanning for the header. And because `new_document`'s version
+/// defaults to 1.4, appending to a 1.7 file wrote a line claiming 1.4.
+#[test]
+fn incremental_save_appends_no_second_file_header() {
+ let mut doc = Document::with_version("1.7");
+ let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog" });
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+ let mut prev_bytes = Vec::new();
+ doc.save_to(&mut prev_bytes).unwrap();
+
+ let loaded = Document::load_mem(&prev_bytes).unwrap();
+ let mut incremental = IncrementalDocument::create_from(prev_bytes.clone(), loaded);
+ let marker: Vec<u8> = b"header-guard".to_vec();
+ let stream = Stream::new(dictionary! {}, marker.clone()).with_compression(false);
+ let new_id = incremental.new_document.add_object(Object::Stream(stream));
+
+ let mut out = Vec::new();
+ incremental.save_to(&mut out).unwrap();
+
+ // The previous revision is reproduced untouched.
+ assert_eq!(&out[..prev_bytes.len()], &prev_bytes[..]);
+
+ // The appended region carries neither a header nor a binary marker: it
+ // begins directly with an indirect object.
+ let appended = &out[prev_bytes.len()..];
+ assert!(
+ !appended.windows(b"%PDF-".len()).any(|w| w == b"%PDF-"),
+ "appended region must not open a second document"
+ );
+ let first = appended
+ .iter()
+ .position(|b| !b" \r\n".contains(b))
+ .expect("appended region is not empty");
+ assert!(
+ appended[first].is_ascii_digit(),
+ "appended region must begin with an indirect object, found {:?}",
+ String::from_utf8_lossy(&appended[first..(first + 16).min(appended.len())])
+ );
+
+ // The result still parses, keeps the version it was built with, and the
+ // appended object reads back.
+ let reloaded = Document::load_mem(&out).unwrap();
+ assert_eq!(reloaded.version, "1.7", "the file's version was rewritten");
+ assert_eq!(
+ reloaded.get_object(new_id).unwrap().as_stream().unwrap().content,
+ marker
+ );
+}
+
+/// Build a minimal document that has everything `EncryptionVersion::V1`
+/// needs to derive an encryption key (a `Root` entry and a file `ID`).
+fn minimal_encryptable_document() -> Document {
+ let mut doc = Document::with_version("1.5");
+ let catalog_id = doc.add_object(lopdf::dictionary! { "Type" => "Catalog" });
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::string_literal(vec![1u8; 16]),
+ Object::string_literal(vec![2u8; 16]),
+ ]),
+ );
+ doc
+}
+
+/// After `decrypt`, `EncryptionState::encrypt_object_id()` must expose the
+/// object id of the `/Encrypt` dictionary that was in the trailer before
+/// decryption — an incremental save needs it to restore `/Encrypt` in the
+/// appended trailer.
+#[test]
+fn decrypt_records_encrypt_object_id() {
+ let mut doc = minimal_encryptable_document();
+
+ let encryption_version = EncryptionVersion::V1 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+ let encryption_state = EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let mut prev_bytes = Vec::new();
+ doc.save_to(&mut prev_bytes).unwrap();
+
+ // Capture the /Encrypt reference id from the on-disk trailer before decrypt.
+ let expected_id = Document::load_mem(&prev_bytes)
+ .unwrap()
+ .trailer
+ .get(b"Encrypt")
+ .unwrap()
+ .as_reference()
+ .unwrap();
+
+ let mut loaded = Document::load_mem(&prev_bytes).unwrap();
+ loaded.decrypt("user").unwrap();
+
+ let recorded = loaded
+ .encryption_state
+ .as_ref()
+ .expect("encryption_state set after decrypt")
+ .encrypt_object_id()
+ .expect("encrypt_object_id recorded during decrypt");
+ assert_eq!(recorded, expected_id);
+}
+
+/// Prepare an encrypted PDF: build a minimal encryptable document, apply the
+/// supplied `EncryptionState`, and save it to bytes.
+fn build_encrypted_pdf(state: &EncryptionState) -> Vec<u8> {
+ let mut doc = minimal_encryptable_document();
+ doc.encrypt(state).unwrap();
+ let mut bytes = Vec::new();
+ doc.save_to(&mut bytes).unwrap();
+ bytes
+}
+
+/// Return the `/Encrypt` object id currently stored in the on-disk trailer
+/// of `bytes` (the file must not be decrypted before calling this).
+fn read_encrypt_id(bytes: &[u8]) -> lopdf::ObjectId {
+ Document::load_mem(bytes)
+ .unwrap()
+ .trailer
+ .get(b"Encrypt")
+ .unwrap()
+ .as_reference()
+ .unwrap()
+}
+
+/// Load `bytes` and immediately decrypt using `password`, returning the
+/// fully-populated `Document`. `Document::load_mem` defers object parsing for
+/// encrypted files that arrive without a password, so tests that need the
+/// content objects present must go through `load_mem_with_options`.
+fn load_and_decrypt(bytes: &[u8], password: &str) -> Document {
+ Document::load_mem_with_options(bytes, LoadOptions::with_password(password)).unwrap()
+}
+
+/// End-to-end verification of an incremental save on a decrypted document:
+/// build encrypted `prev_bytes`, decrypt them, append a new plaintext-marker
+/// stream, save incrementally, then check that the appended region does not
+/// leak the plaintext, that decrypt+read still round-trips, and that the
+/// trailer's `/Encrypt` reference resolves to the original id.
+fn encrypted_incremental_round_trip(label: &str, state: EncryptionState) {
+ let prev_bytes = build_encrypted_pdf(&state);
+ let original_encrypt_id = read_encrypt_id(&prev_bytes);
+
+ let loaded = load_and_decrypt(&prev_bytes, "user");
+ assert!(
+ loaded.encryption_state.as_ref().unwrap().encrypt_object_id().is_some(),
+ "{label}: encrypt_object_id must be recorded during load-and-decrypt"
+ );
+
+ let mut incremental = IncrementalDocument::create_from(prev_bytes.clone(), loaded);
+ let marker: Vec<u8> = format!("PR520-MARKER-{label}").into_bytes();
+ let stream = Stream::new(dictionary! {}, marker.clone()).with_compression(false);
+ let new_stream_id = incremental.new_document.add_object(Object::Stream(stream));
+
+ let mut out = Vec::new();
+ incremental.save_to(&mut out).unwrap();
+
+ // Assert A: the plaintext marker must not appear anywhere in the
+ // appended (encrypted) region.
+ let appended = &out[prev_bytes.len()..];
+ assert!(
+ !appended.windows(marker.len()).any(|w| w == marker.as_slice()),
+ "{label}: plaintext marker leaked in the appended region"
+ );
+
+ // Assert B: round-trip. Reloading and decrypting the appended file must
+ // reveal the marker again.
+ let reloaded = load_and_decrypt(&out, "user");
+ let stream = reloaded.get_object(new_stream_id).unwrap().as_stream().unwrap();
+ assert_eq!(
+ stream.content, marker,
+ "{label}: appended stream content mismatch after round-trip"
+ );
+
+ // Assert C: the trailer's /Encrypt reference in the appended file resolves
+ // to the same object id as the original encrypted revision. The dictionary
+ // bytes themselves live in the previous revision and are still intact.
+ let round_encrypt_id = read_encrypt_id(&out);
+ assert_eq!(
+ round_encrypt_id, original_encrypt_id,
+ "{label}: trailer /Encrypt reference mismatch after round-trip"
+ );
+}
+
+/// Incremental save of a document decrypted from V1 (RC4-40) round-trips —
+/// replaces the earlier PR #521 rejection test now that #520 supports this.
+#[test]
+fn incremental_save_of_decrypted_document_v1_round_trip() {
+ let doc = minimal_encryptable_document();
+ let state = EncryptionState::try_from(EncryptionVersion::V1 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ encrypted_incremental_round_trip("V1", state);
+}
+
+#[test]
+fn incremental_save_of_decrypted_document_v2_round_trip() {
+ let doc = minimal_encryptable_document();
+ let state = EncryptionState::try_from(EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ key_length: 128,
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ encrypted_incremental_round_trip("V2", state);
+}
+
+/// V2 (RC4-128) × `CrossReferenceTable`: exercises the classical
+/// `trailer <<...>>` writer path (`Document::write_trailer`) rather than the
+/// xref-stream path (`Document::write_cross_reference_stream`). Both paths
+/// serialize `self.new_document.trailer`, and the `/Encrypt` swap in
+/// `IncrementalDocument::save_internal` targets exactly that field, so a
+/// table-based prior revision must produce an appended trailer that carries
+/// `/Encrypt` — verified via `read_encrypt_id` plus a byte-level check that
+/// the classical `trailer` keyword appears in the appended region.
+#[test]
+fn incremental_save_of_decrypted_document_v2_cross_reference_table_round_trip() {
+ let mut doc = minimal_encryptable_document();
+ doc.reference_table.cross_reference_type = XrefType::CrossReferenceTable;
+ let state = EncryptionState::try_from(EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ key_length: 128,
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ doc.encrypt(&state).unwrap();
+ let mut prev_bytes = Vec::new();
+ doc.save_to(&mut prev_bytes).unwrap();
+
+ // Sanity check on the fixture: the base revision must use the classical
+ // `trailer` keyword. If this fails, the test setup slipped back to the
+ // xref-stream path and no longer covers what it claims to cover.
+ let trailer_keyword: &[u8] = b"trailer\n";
+ assert!(
+ prev_bytes.windows(trailer_keyword.len()).any(|w| w == trailer_keyword),
+ "base revision must use classical trailer for this test to be meaningful"
+ );
+
+ let original_encrypt_id = read_encrypt_id(&prev_bytes);
+
+ let loaded = load_and_decrypt(&prev_bytes, "user");
+ assert!(
+ matches!(
+ loaded.reference_table.cross_reference_type,
+ XrefType::CrossReferenceTable
+ ),
+ "loaded document must retain the CrossReferenceTable format"
+ );
+
+ let mut incremental = IncrementalDocument::create_from(prev_bytes.clone(), loaded);
+ let marker: Vec<u8> = b"PR520-MARKER-V2-Table".to_vec();
+ let stream = Stream::new(dictionary! {}, marker.clone()).with_compression(false);
+ let new_stream_id = incremental.new_document.add_object(Object::Stream(stream));
+
+ let mut out = Vec::new();
+ incremental.save_to(&mut out).unwrap();
+
+ let appended = &out[prev_bytes.len()..];
+
+ // The appended region must go through the classical `trailer` path,
+ // which is where `write_trailer` reads `self.trailer` — the swap target.
+ assert!(
+ appended.windows(trailer_keyword.len()).any(|w| w == trailer_keyword),
+ "appended region must use classical trailer (CrossReferenceTable path)"
+ );
+
+ // Assert A: no plaintext leak in the appended region.
+ assert!(
+ !appended.windows(marker.len()).any(|w| w == marker.as_slice()),
+ "V2/table: plaintext marker leaked in the appended region"
+ );
+
+ // Assert B: round-trip.
+ let reloaded = load_and_decrypt(&out, "user");
+ let stream = reloaded.get_object(new_stream_id).unwrap().as_stream().unwrap();
+ assert_eq!(
+ stream.content, marker,
+ "V2/table: appended stream content mismatch after round-trip"
+ );
+
+ // Assert C: the trailer's /Encrypt reference resolves to the original id.
+ let round_encrypt_id = read_encrypt_id(&out);
+ assert_eq!(
+ round_encrypt_id, original_encrypt_id,
+ "V2/table: trailer /Encrypt reference mismatch after round-trip"
+ );
+}
+
+#[test]
+fn incremental_save_of_decrypted_document_v4_round_trip() {
+ let doc = minimal_encryptable_document();
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes128CryptFilter);
+ let state = EncryptionState::try_from(EncryptionVersion::V4 {
+ document: &doc,
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ encrypted_incremental_round_trip("V4", state);
+}
+
+#[test]
+fn incremental_save_of_decrypted_document_v5_round_trip() {
+ // Fixed key: this is a deterministic test; `Aes256CryptFilter` combined
+ // with V5's per-object IV keeps the outputs distinct anyway.
+ let file_encryption_key = [7u8; 32];
+ let crypt_filter: Arc<dyn CryptFilter> = Arc::new(Aes256CryptFilter);
+ let state = EncryptionState::try_from(EncryptionVersion::V5 {
+ encrypt_metadata: true,
+ crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), crypt_filter)]),
+ file_encryption_key: &file_encryption_key,
+ stream_filter: b"StdCF".to_vec(),
+ string_filter: b"StdCF".to_vec(),
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ encrypted_incremental_round_trip("V5", state);
+}
+
+/// Regression guard for the "clone before encrypt" invariant: two successive
+/// incremental saves on the same `IncrementalDocument` must not double-encrypt
+/// the objects added in the earlier round. If we mutated in-place, the second
+/// save would re-encrypt already-encrypted bytes and decrypt would return
+/// garbage instead of the marker.
+#[test]
+fn incremental_save_of_decrypted_document_does_not_double_encrypt_on_repeated_save() {
+ let doc = minimal_encryptable_document();
+ let state = EncryptionState::try_from(EncryptionVersion::V1 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ let prev_bytes = build_encrypted_pdf(&state);
+
+ let loaded = load_and_decrypt(&prev_bytes, "user");
+ let mut incremental = IncrementalDocument::create_from(prev_bytes, loaded);
+
+ let marker_a: Vec<u8> = b"PR520-A".to_vec();
+ let stream_a = Stream::new(dictionary! {}, marker_a.clone()).with_compression(false);
+ let id_a = incremental.new_document.add_object(Object::Stream(stream_a));
+
+ let mut buf1 = Vec::new();
+ incremental.save_to(&mut buf1).unwrap();
+
+ let marker_b: Vec<u8> = b"PR520-B".to_vec();
+ let stream_b = Stream::new(dictionary! {}, marker_b.clone()).with_compression(false);
+ let id_b = incremental.new_document.add_object(Object::Stream(stream_b));
+
+ let mut buf2 = Vec::new();
+ incremental.save_to(&mut buf2).unwrap();
+
+ let reloaded = load_and_decrypt(&buf2, "user");
+ let content_a = reloaded.get_object(id_a).unwrap().as_stream().unwrap().content.clone();
+ let content_b = reloaded.get_object(id_b).unwrap().as_stream().unwrap().content.clone();
+ assert_eq!(
+ content_a, marker_a,
+ "stream A must survive a second incremental save without double-encryption"
+ );
+ assert_eq!(
+ content_b, marker_b,
+ "stream B must be readable after the second incremental save"
+ );
+}
+
+/// Incremental save of a still-*encrypted* (never decrypted) document must
+/// also be rejected: the trailer still carries `/Encrypt`, but any newly
+/// appended objects would be written as plaintext, which readers would
+/// misinterpret as ciphertext.
+#[test]
+fn incremental_save_of_still_encrypted_document_is_rejected() {
+ let mut doc = minimal_encryptable_document();
+
+ let encryption_version = EncryptionVersion::V1 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ };
+ let encryption_state = EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let mut prev_bytes = Vec::new();
+ doc.save_to(&mut prev_bytes).unwrap();
+
+ // Load without decrypting: `is_encrypted()` stays true.
+ let loaded = Document::load_mem(&prev_bytes).unwrap();
+ assert!(loaded.is_encrypted());
+ assert!(!loaded.was_encrypted());
+
+ let mut incremental = IncrementalDocument::create_from(prev_bytes, loaded);
+ incremental.new_document.add_object(Object::Integer(42));
+
+ let mut out = Vec::new();
+ let err = incremental.save_to(&mut out).unwrap_err();
+ assert_eq!(err.kind(), io::ErrorKind::Unsupported);
+}
+
+/// `IncrementalDocument::save(path)` must not truncate a pre-existing file
+/// when the incremental save is unsupported. Prior to this check the guard
+/// ran only after `File::create` had already zeroed the target.
+#[test]
+fn incremental_save_to_path_does_not_truncate_on_unsupported_input() {
+ let mut doc = minimal_encryptable_document();
+ let encryption_state = EncryptionState::try_from(EncryptionVersion::V1 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ permissions: Permissions::all(),
+ })
+ .unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let mut prev_bytes = Vec::new();
+ doc.save_to(&mut prev_bytes).unwrap();
+
+ // Load without decrypting: this is the still-encrypted (unsupported) case.
+ let loaded = Document::load_mem(&prev_bytes).unwrap();
+ let mut incremental = IncrementalDocument::create_from(prev_bytes, loaded);
+
+ let temp_dir = tempdir().unwrap();
+ let target_path = temp_dir.path().join("existing.pdf");
+ let sentinel: &[u8] = b"do-not-truncate-me";
+ fs::write(&target_path, sentinel).unwrap();
+
+ let err = incremental.save(&target_path).unwrap_err();
+ assert_eq!(err.kind(), io::ErrorKind::Unsupported);
+
+ // File must be untouched on disk.
+ let on_disk = fs::read(&target_path).unwrap();
+ assert_eq!(
+ on_disk, sentinel,
+ "unsupported save must not truncate or overwrite the target file"
+ );
+}
diff --git a/vendor/lopdf/tests/linearized_objstm_test.rs b/vendor/lopdf/tests/linearized_objstm_test.rs
new file mode 100644
index 000000000..659969d6c
--- /dev/null
+++ b/vendor/lopdf/tests/linearized_objstm_test.rs
@@ -0,0 +1,131 @@
+use lopdf::Document;
+
+/// Build a minimal PDF where two ObjStm streams contain conflicting versions
+/// of the same object (the Pages tree root). The xref Compressed entry points
+/// to the higher-numbered ObjStm as authoritative, but the lower-numbered one
+/// is processed first during loading.
+///
+/// Without the fix in load_objects_raw, the stale copy from the lower-numbered
+/// ObjStm would win via or_insert, causing the document to report fewer pages.
+fn build_conflicting_objstm_pdf() -> Vec<u8> {
+ let mut buf = Vec::new();
+
+ // Header
+ buf.extend_from_slice(b"%PDF-1.5\n");
+
+ // Object 1: Catalog
+ let off_1 = buf.len();
+ buf.extend_from_slice(b"1 0 obj\n<</Type/Catalog/Pages 3 0 R>>\nendobj\n");
+
+ // Object 2: ObjStm with STALE copy of object 3 (Count=1, only 1 kid)
+ let off_2 = buf.len();
+ let stale_data = b"3 0 <</Type/Pages/Count 1/Kids[5 0 R]>>";
+ buf.extend_from_slice(
+ format!(
+ "2 0 obj\n<</Type/ObjStm/N 1/First 4/Length {}>>\nstream\n",
+ stale_data.len()
+ )
+ .as_bytes(),
+ );
+ buf.extend_from_slice(stale_data);
+ buf.extend_from_slice(b"\nendstream\nendobj\n");
+
+ // Object 4: ObjStm with CORRECT copy of object 3 (Count=2, 2 kids)
+ let off_4 = buf.len();
+ let correct_data = b"3 0 <</Type/Pages/Count 2/Kids[5 0 R 6 0 R]>>";
+ buf.extend_from_slice(
+ format!(
+ "4 0 obj\n<</Type/ObjStm/N 1/First 4/Length {}>>\nstream\n",
+ correct_data.len()
+ )
+ .as_bytes(),
+ );
+ buf.extend_from_slice(correct_data);
+ buf.extend_from_slice(b"\nendstream\nendobj\n");
+
+ // Object 5: Page
+ let off_5 = buf.len();
+ buf.extend_from_slice(b"5 0 obj\n<</Type/Page/Parent 3 0 R/MediaBox[0 0 612 792]>>\nendobj\n");
+
+ // Object 6: Page
+ let off_6 = buf.len();
+ buf.extend_from_slice(b"6 0 obj\n<</Type/Page/Parent 3 0 R/MediaBox[0 0 612 792]>>\nendobj\n");
+
+ // Object 7: Cross-reference stream
+ // W=[1 3 1]: type (1 byte), field2 (3 bytes), field3 (1 byte)
+ // Entries for objects 0-7:
+ // 0: Free
+ // 1: Normal (Catalog)
+ // 2: Normal (stale ObjStm)
+ // 3: Compressed in container=4, index=0 <-- authoritative
+ // 4: Normal (correct ObjStm)
+ // 5: Normal (Page)
+ // 6: Normal (Page)
+ // 7: Normal (xref stream itself)
+ let off_7 = buf.len();
+
+ let mut xref_data = Vec::new();
+ let offsets = [
+ 0u32,
+ off_1 as u32,
+ off_2 as u32,
+ 0,
+ off_4 as u32,
+ off_5 as u32,
+ off_6 as u32,
+ off_7 as u32,
+ ];
+
+ // Object 0: Free
+ xref_data.extend_from_slice(&[0, 0, 0, 0, 0]);
+
+ // Objects 1, 2: Normal
+ for &off in &offsets[1..=2] {
+ xref_data.push(1);
+ xref_data.push((off >> 16) as u8);
+ xref_data.push((off >> 8) as u8);
+ xref_data.push(off as u8);
+ xref_data.push(0);
+ }
+
+ // Object 3: Compressed { container: 4, index: 0 }
+ xref_data.push(2);
+ xref_data.extend_from_slice(&[0, 0, 4]); // container = 4
+ xref_data.push(0); // index = 0
+
+ // Objects 4, 5, 6, 7: Normal
+ for &off in &offsets[4..=7] {
+ xref_data.push(1);
+ xref_data.push((off >> 16) as u8);
+ xref_data.push((off >> 8) as u8);
+ xref_data.push(off as u8);
+ xref_data.push(0);
+ }
+
+ buf.extend_from_slice(
+ format!(
+ "7 0 obj\n<</Type/XRef/Size 8/W[1 3 1]/Root 1 0 R/Length {}>>\nstream\n",
+ xref_data.len()
+ )
+ .as_bytes(),
+ );
+ buf.extend_from_slice(&xref_data);
+ buf.extend_from_slice(b"\nendstream\nendobj\n");
+
+ buf.extend_from_slice(format!("startxref\n{}\n%%EOF", off_7).as_bytes());
+ buf
+}
+
+#[test]
+fn test_conflicting_objstm_uses_xref_container() {
+ let pdf = build_conflicting_objstm_pdf();
+ let doc = Document::load_mem(&pdf).unwrap();
+
+ // The xref says object 3 (Pages root) belongs to ObjStm 4 (Count=2).
+ // ObjStm 2 has a stale copy with Count=1. The correct version must win.
+ assert_eq!(
+ doc.get_pages().len(),
+ 2,
+ "Should load 2 pages from ObjStm 4, not 1 from stale ObjStm 2"
+ );
+}
diff --git a/vendor/lopdf/tests/load_options_test.rs b/vendor/lopdf/tests/load_options_test.rs
new file mode 100644
index 000000000..04294eec8
--- /dev/null
+++ b/vendor/lopdf/tests/load_options_test.rs
@@ -0,0 +1,216 @@
+#[cfg(not(feature = "async"))]
+mod sync_tests {
+ use lopdf::{Document, Error, LoadOptions, Object, ParseError};
+ use std::assert_matches;
+ use std::fs::File;
+
+ #[test]
+ fn load_options_default() {
+ let opts = LoadOptions::default();
+ assert!(opts.password.is_none());
+ assert!(opts.filter.is_none());
+ assert!(!opts.strict);
+ }
+
+ #[test]
+ fn load_options_with_password() {
+ let opts = LoadOptions::with_password("secret");
+ assert_eq!(opts.password.as_deref(), Some("secret"));
+ assert!(opts.filter.is_none());
+ assert!(!opts.strict);
+ }
+
+ #[test]
+ fn load_options_with_filter() {
+ fn my_filter(id: (u32, u16), obj: &mut Object) -> Option<((u32, u16), Object)> {
+ Some((id, obj.clone()))
+ }
+ let opts = LoadOptions::with_filter(my_filter);
+ assert!(opts.password.is_none());
+ assert!(opts.filter.is_some());
+ assert!(!opts.strict);
+ }
+
+ #[test]
+ fn load_options_debug_masks_password() {
+ let opts = LoadOptions::with_password("supersecret");
+ let debug = format!("{:?}", opts);
+ assert!(
+ !debug.contains("supersecret"),
+ "password should be masked in Debug output"
+ );
+ assert!(debug.contains("***"), "masked password should show ***");
+ }
+
+ #[test]
+ fn load_options_debug_no_password() {
+ let opts = LoadOptions::default();
+ let debug = format!("{:?}", opts);
+ assert!(debug.contains("None"));
+ }
+
+ #[test]
+ fn load_with_options_default_matches_load() {
+ let doc1 = Document::load("assets/example.pdf").unwrap();
+ let doc2 = Document::load_with_options("assets/example.pdf", LoadOptions::default()).unwrap();
+ assert_eq!(doc1.version, doc2.version);
+ assert_eq!(doc1.objects.len(), doc2.objects.len());
+ }
+
+ #[test]
+ fn load_from_with_options_default_matches_load_from() {
+ let doc1 = Document::load_from(File::open("assets/example.pdf").unwrap()).unwrap();
+ let doc2 = Document::load_from_with_options(File::open("assets/example.pdf").unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(doc1.version, doc2.version);
+ assert_eq!(doc1.objects.len(), doc2.objects.len());
+ }
+
+ #[test]
+ fn load_mem_with_options_default_matches_load_mem() {
+ let buf = std::fs::read("assets/example.pdf").unwrap();
+ let doc1 = Document::load_mem(&buf).unwrap();
+ let doc2 = Document::load_mem_with_options(&buf, LoadOptions::default()).unwrap();
+ assert_eq!(doc1.version, doc2.version);
+ assert_eq!(doc1.objects.len(), doc2.objects.len());
+ }
+
+ #[test]
+ fn load_with_options_filter_removes_objects() {
+ // Filter that drops all stream objects
+ fn drop_streams(id: (u32, u16), obj: &mut Object) -> Option<((u32, u16), Object)> {
+ if obj.as_stream().is_ok() {
+ None
+ } else {
+ Some((id, obj.clone()))
+ }
+ }
+
+ let full = Document::load("assets/example.pdf").unwrap();
+ let filtered =
+ Document::load_with_options("assets/example.pdf", LoadOptions::with_filter(drop_streams)).unwrap();
+
+ let full_streams = full.objects.values().filter(|o| o.as_stream().is_ok()).count();
+ let filtered_streams = filtered.objects.values().filter(|o| o.as_stream().is_ok()).count();
+
+ assert!(full_streams > 0, "example.pdf should have streams");
+ assert_eq!(filtered_streams, 0, "filter should have removed all streams");
+ assert!(
+ filtered.objects.len() < full.objects.len(),
+ "filtered doc should have fewer objects"
+ );
+ }
+
+ #[test]
+ fn load_mem_with_options_filter() {
+ // Filter that only keeps dictionary objects
+ fn only_dicts(id: (u32, u16), obj: &mut Object) -> Option<((u32, u16), Object)> {
+ if obj.as_dict().is_ok() {
+ Some((id, obj.clone()))
+ } else {
+ None
+ }
+ }
+
+ let buf = std::fs::read("assets/example.pdf").unwrap();
+ let filtered = Document::load_mem_with_options(&buf, LoadOptions::with_filter(only_dicts)).unwrap();
+
+ // All remaining objects should be dictionaries
+ for obj in filtered.objects.values() {
+ assert!(obj.as_dict().is_ok(), "all objects should be dictionaries after filter");
+ }
+ }
+
+ #[test]
+ fn load_with_options_strict_false_loads_normally() {
+ let doc = Document::load_with_options(
+ "assets/example.pdf",
+ LoadOptions {
+ strict: false,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(doc.version, "1.5");
+ }
+
+ #[test]
+ fn load_with_options_strict_true_loads_valid_pdf() {
+ // strict=true should still load a valid, conforming PDF
+ let doc = Document::load_with_options(
+ "assets/example.pdf",
+ LoadOptions {
+ strict: true,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(doc.version, "1.5");
+ }
+
+ #[test]
+ fn load_with_options_password_on_encrypted_pdf() {
+ let doc = Document::load_with_options("assets/encrypted.pdf", LoadOptions::with_password("")).unwrap();
+ assert!(!doc.is_encrypted());
+ assert!(doc.encryption_state.is_some());
+ let pages = doc.get_pages();
+ assert_eq!(pages.len(), 1);
+ }
+
+ #[test]
+ fn load_mem_with_options_password_on_encrypted_pdf() {
+ let buf = std::fs::read("assets/encrypted.pdf").unwrap();
+ let doc = Document::load_mem_with_options(&buf, LoadOptions::with_password("")).unwrap();
+ assert!(!doc.is_encrypted());
+ assert!(doc.encryption_state.is_some());
+ }
+
+ #[test]
+ fn load_with_options_combined_password_and_strict() {
+ let opts = LoadOptions {
+ password: Some(String::new()),
+ strict: true,
+ ..Default::default()
+ };
+ let doc = Document::load_with_options("assets/encrypted.pdf", opts).unwrap();
+ assert!(!doc.is_encrypted());
+ assert!(doc.encryption_state.is_some());
+ }
+
+ #[test]
+ fn load_with_options_nonexistent_file() {
+ let result = Document::load_with_options("nonexistent.pdf", LoadOptions::default());
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn strict_rejects_binary_bytes_on_header_line() {
+ // Minimal PDF-like buffer with binary bytes on the header line.
+ // Strict mode should reject this with InvalidFileHeader.
+ let buf = b"%PDF-1.3 \xb0\x9f\x92\x9c\r%%EOF\r";
+ let result = Document::load_mem_with_options(
+ buf,
+ LoadOptions {
+ strict: true,
+ ..Default::default()
+ },
+ );
+ assert_matches!(result.unwrap_err(), Error::Parse(ParseError::InvalidFileHeader));
+ }
+
+ #[test]
+ fn lenient_accepts_binary_bytes_on_header_line() {
+ // Same buffer, but lenient (default) mode should parse the header
+ // successfully (it will fail later because the rest isn't a real PDF,
+ // but the header itself should be accepted).
+ let buf = b"%PDF-1.3 \xb0\x9f\x92\x9c\r%%EOF\r";
+ let result = Document::load_mem_with_options(buf, LoadOptions::default());
+ // The error should NOT be InvalidFileHeader — the header parsed fine.
+ if let Err(e) = &result {
+ assert!(
+ !e.to_string().contains("invalid file header"),
+ "lenient mode should accept binary bytes on header line, got: {e}"
+ );
+ }
+ }
+}
diff --git a/vendor/lopdf/tests/metadata_test.rs b/vendor/lopdf/tests/metadata_test.rs
new file mode 100644
index 000000000..309be4639
--- /dev/null
+++ b/vendor/lopdf/tests/metadata_test.rs
@@ -0,0 +1,335 @@
+use lopdf::Document;
+
+#[test]
+fn test_metadata_extraction_basic() {
+ let buffer = std::fs::read("assets/example.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+
+ assert_eq!(metadata.version, "1.5");
+ assert!(metadata.page_count > 0);
+ assert!(!metadata.encrypted);
+}
+
+#[test]
+fn test_metadata_extraction_page_count() {
+ let buffer = std::fs::read("assets/example.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+ assert!(metadata.page_count > 0);
+
+ let buffer = std::fs::read("assets/example.pdf").unwrap();
+ let doc = Document::load_mem(&buffer).unwrap();
+ let pages = doc.get_pages();
+ assert_eq!(metadata.page_count, pages.len() as u32);
+}
+
+#[test]
+fn test_metadata_extraction_unicode() {
+ let buffer = std::fs::read("assets/unicode.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+ assert!(metadata.page_count > 0);
+}
+
+#[test]
+fn test_metadata_extraction_from_memory() {
+ let buffer = std::fs::read("assets/example.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+
+ assert_eq!(metadata.version, "1.5");
+ assert!(metadata.page_count > 0);
+}
+
+#[test]
+fn test_metadata_extraction_incremental() {
+ let buffer = std::fs::read("assets/Incremental.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+ assert!(metadata.page_count > 0);
+}
+
+#[test]
+fn test_metadata_extraction_annotation_demo() {
+ let buffer = std::fs::read("assets/AnnotationDemo.pdf").unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+ assert!(metadata.page_count > 0);
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_metadata_extraction_encrypted_empty_password() {
+ let mut doc = Document::with_version("1.5");
+
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ lopdf::Object::Array(vec![
+ lopdf::Object::String(id1, lopdf::StringFormat::Literal),
+ lopdf::Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![lopdf::Object::Reference((3, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), lopdf::Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => lopdf::Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ };
+ doc.objects.insert((3, 0), lopdf::Object::Dictionary(page_dict));
+
+ let info_dict = lopdf::dictionary! {
+ "Title" => lopdf::Object::String(b"Test Encrypted PDF".to_vec(), lopdf::StringFormat::Literal),
+ "Author" => lopdf::Object::String(b"Test Author".to_vec(), lopdf::StringFormat::Literal),
+ "Subject" => lopdf::Object::String(b"Test Subject".to_vec(), lopdf::StringFormat::Literal)
+ };
+ let info_id = doc.add_object(info_dict);
+ doc.trailer.set("Info", lopdf::Object::Reference(info_id));
+
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "",
+ user_password: "",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_encrypted_metadata.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ let metadata = Document::load_metadata(&encrypted_path).unwrap();
+ assert_eq!(metadata.title, Some("Test Encrypted PDF".to_string()));
+ assert_eq!(metadata.author, Some("Test Author".to_string()));
+ assert_eq!(metadata.subject, Some("Test Subject".to_string()));
+ assert_eq!(metadata.page_count, 1);
+ assert!(metadata.encrypted);
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_metadata_extraction_encrypted_with_password() {
+ let mut doc = Document::with_version("1.5");
+
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ lopdf::Object::Array(vec![
+ lopdf::Object::String(id1, lopdf::StringFormat::Literal),
+ lopdf::Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![lopdf::Object::Reference((3, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), lopdf::Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => lopdf::Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ };
+ doc.objects.insert((3, 0), lopdf::Object::Dictionary(page_dict));
+
+ let info_dict = lopdf::dictionary! {
+ "Title" => lopdf::Object::String(b"Password Protected PDF".to_vec(), lopdf::StringFormat::Literal),
+ "Author" => lopdf::Object::String(b"Protected Author".to_vec(), lopdf::StringFormat::Literal)
+ };
+ let info_id = doc.add_object(info_dict);
+ doc.trailer.set("Info", lopdf::Object::Reference(info_id));
+
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner_pass",
+ user_password: "user_pass",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_password_metadata.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ let metadata = Document::load_metadata_with_password(&encrypted_path, "user_pass").unwrap();
+ assert_eq!(metadata.title, Some("Password Protected PDF".to_string()));
+ assert_eq!(metadata.author, Some("Protected Author".to_string()));
+ assert_eq!(metadata.page_count, 1);
+
+ let buffer = std::fs::read(&encrypted_path).unwrap();
+ let metadata_mem = Document::load_metadata_mem_with_password(&buffer, "user_pass").unwrap();
+ assert_eq!(metadata_mem.title, Some("Password Protected PDF".to_string()));
+ assert_eq!(metadata_mem.author, Some("Protected Author".to_string()));
+ assert_eq!(metadata_mem.page_count, 1);
+ assert!(metadata.encrypted);
+ assert!(metadata_mem.encrypted);
+
+ // Without the password, the loader no longer fails: it reports `encrypted`
+ // and omits the (undecryptable) Info fields rather than erroring.
+ let metadata_no_pw = Document::load_metadata_mem(&buffer).unwrap();
+ assert!(metadata_no_pw.encrypted);
+ assert_eq!(metadata_no_pw.title, None);
+ assert_eq!(metadata_no_pw.author, None);
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn test_metadata_extraction_encrypted_wrong_password() {
+ let mut doc = Document::with_version("1.5");
+
+ let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ doc.trailer.set(
+ "ID",
+ lopdf::Object::Array(vec![
+ lopdf::Object::String(id1, lopdf::StringFormat::Literal),
+ lopdf::Object::String(id2, lopdf::StringFormat::Literal),
+ ]),
+ );
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![lopdf::Object::Reference((3, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), lopdf::Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => lopdf::Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ };
+ doc.objects.insert((3, 0), lopdf::Object::Dictionary(page_dict));
+
+ let encryption_version = lopdf::EncryptionVersion::V2 {
+ document: &doc,
+ owner_password: "owner",
+ user_password: "user",
+ key_length: 128,
+ permissions: lopdf::Permissions::all(),
+ };
+
+ let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
+ doc.encrypt(&encryption_state).unwrap();
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let encrypted_path = temp_dir.path().join("test_wrong_password.pdf");
+ doc.save(&encrypted_path).unwrap();
+
+ let result = Document::load_metadata_with_password(&encrypted_path, "wrong_password");
+ assert!(result.is_err());
+ assert!(matches!(result.unwrap_err(), lopdf::Error::InvalidPassword));
+}
+
+/// Verifies that custom (non-standard) Info dictionary entries are preserved on
+/// `PdfMetadata::custom`, while the standard fields remain available through
+/// their typed accessors. This is the path used to extract producer-specific
+/// metadata such as Microsoft Information Protection labels
+/// (`MSIP_Label_{GUID}_{Property}`) without loading the full document.
+#[test]
+fn test_metadata_extraction_preserves_custom_info_entries() {
+ let mut doc = Document::with_version("1.5");
+
+ let catalog_dict = lopdf::dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference((2, 0))
+ };
+ let catalog_id = doc.add_object(catalog_dict);
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog_id));
+
+ let pages_dict = lopdf::dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![lopdf::Object::Reference((3, 0))],
+ "Count" => 1
+ };
+ doc.objects.insert((2, 0), lopdf::Object::Dictionary(pages_dict));
+
+ let page_dict = lopdf::dictionary! {
+ "Type" => "Page",
+ "Parent" => lopdf::Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ };
+ doc.objects.insert((3, 0), lopdf::Object::Dictionary(page_dict));
+
+ let mip_guid_enabled = "MSIP_Label_754d9351-9ade-4bd5-893a-95071572330d_Enabled";
+ let mip_guid_name = "MSIP_Label_754d9351-9ade-4bd5-893a-95071572330d_Name";
+
+ let info_dict = lopdf::dictionary! {
+ "Title" => lopdf::Object::String(b"Doc with custom info".to_vec(), lopdf::StringFormat::Literal),
+ "Producer" => lopdf::Object::String(b"Test Suite".to_vec(), lopdf::StringFormat::Literal),
+ mip_guid_enabled => lopdf::Object::String(b"True".to_vec(), lopdf::StringFormat::Literal),
+ mip_guid_name => lopdf::Object::String(b"Confidential".to_vec(), lopdf::StringFormat::Literal),
+ "AppCustomCounter" => lopdf::Object::Integer(42)
+ };
+ let info_id = doc.add_object(info_dict);
+ doc.trailer.set("Info", lopdf::Object::Reference(info_id));
+
+ let temp_dir = tempfile::tempdir().unwrap();
+ let path = temp_dir.path().join("test_custom_info.pdf");
+ doc.save(&path).unwrap();
+
+ let buffer = std::fs::read(&path).unwrap();
+ let metadata = Document::load_metadata_mem(&buffer).unwrap();
+
+ // Standard fields still populated.
+ assert_eq!(metadata.title, Some("Doc with custom info".to_string()));
+ assert_eq!(metadata.producer, Some("Test Suite".to_string()));
+
+ // Custom fields preserved on the new `custom` map.
+ assert_eq!(metadata.custom.len(), 3);
+
+ let enabled = metadata
+ .custom
+ .get(mip_guid_enabled.as_bytes())
+ .expect("MIP Enabled entry preserved");
+ assert!(matches!(enabled, lopdf::Object::String(bytes, _) if bytes == b"True"));
+
+ let name = metadata
+ .custom
+ .get(mip_guid_name.as_bytes())
+ .expect("MIP Name entry preserved");
+ assert!(matches!(name, lopdf::Object::String(bytes, _) if bytes == b"Confidential"));
+
+ let counter = metadata
+ .custom
+ .get(&b"AppCustomCounter"[..])
+ .expect("non-string custom entry preserved");
+ assert!(matches!(counter, lopdf::Object::Integer(42)));
+
+ // Standard keys must NOT leak into `custom`.
+ assert!(!metadata.custom.contains_key(&b"Title"[..]));
+ assert!(!metadata.custom.contains_key(&b"Producer"[..]));
+}
diff --git a/vendor/lopdf/tests/modify.rs b/vendor/lopdf/tests/modify.rs
new file mode 100644
index 000000000..3740369ea
--- /dev/null
+++ b/vendor/lopdf/tests/modify.rs
@@ -0,0 +1,168 @@
+#[cfg(not(feature = "async"))]
+use lopdf::{Document, Object};
+
+#[test]
+#[cfg(all(test, not(feature = "async")))]
+fn test_get_object() {
+ use self::Object;
+ use lopdf::Dictionary as LoDictionary;
+ use lopdf::Stream as LoStream;
+
+ let mut doc = Document::new();
+ let id = doc.add_object(Object::string_literal("test"));
+ let id2 = doc.add_object(Object::Stream(LoStream::new(
+ LoDictionary::new(),
+ "stream".as_bytes().to_vec(),
+ )));
+
+ println!("{:?}", id);
+ println!("{:?}", id2);
+
+ let obj1_exists = doc.get_object(id).is_ok();
+ let obj2_exists = doc.get_object(id2).is_ok();
+
+ assert!(obj1_exists);
+ assert!(obj2_exists);
+}
+
+#[cfg(all(test, not(feature = "async")))]
+mod tests_with_parsing {
+ use super::*;
+ use lopdf::Result;
+
+ fn modify_text() -> Result<bool> {
+ let mut doc = Document::load("assets/example.pdf")?;
+ doc.version = "1.4".to_string();
+ if let Some(Object::Stream(stream)) = doc.objects.get_mut(&(4, 0)) {
+ let mut content = stream.decode_content().unwrap();
+ content.operations[3].operands[0] = Object::string_literal("Modified text!");
+ stream.set_content(content.encode().unwrap());
+ }
+
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir()?;
+ let file_path = temp_dir.path().join("test_3_modify.pdf");
+ doc.save(file_path)?;
+ Ok(true)
+ }
+
+ #[test]
+ fn test_modify() {
+ assert!(modify_text().unwrap());
+ }
+
+ fn replace_text() -> Result<Document> {
+ let mut doc = Document::load("assets/example.pdf")?;
+ doc.replace_text(1, "Hello World!", "Modified text!", None)?;
+
+ // Create temporary folder to store file.
+ let temp_dir = tempfile::tempdir()?;
+ let file_path = temp_dir.path().join("test_4_unicode_replace.pdf");
+ doc.save(&file_path)?;
+
+ let doc = Document::load(file_path)?;
+ Ok(doc)
+ }
+
+ #[test]
+ fn test_replace() {
+ assert_eq!(replace_text().unwrap().extract_text(&[1]).unwrap(), "Modified text!\n");
+ }
+
+ fn replace_unicode_text() -> Result<Document> {
+ let mut doc = Document::load("assets/unicode.pdf")?;
+ doc.replace_text(1, "😀", "🔧2", Some("🔨"))?;
+
+ let temp_dir = tempfile::tempdir()?;
+ let file_path = temp_dir.path().join("test_4_unicode_replace.pdf");
+ doc.save(&file_path)?;
+
+ let doc = Document::load(file_path)?;
+ Ok(doc)
+ }
+
+ #[test]
+ fn test_unicode_replace() {
+ let text = replace_unicode_text().unwrap().extract_text(&[1]).unwrap();
+ assert_eq!(text, "🔧🔨\n🔧\n🔨\n");
+ }
+
+ fn build_doc_with_tj_array(content_bytes: Vec<u8>) -> Document {
+ use lopdf::dictionary;
+
+ let mut doc = Document::with_version("1.5");
+
+ let pages_id = doc.new_object_id();
+
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica",
+ });
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+
+ let content_id = doc.add_object(lopdf::Stream::new(dictionary! {}, content_bytes));
+
+ let single_page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Resources" => resources_id,
+ "Contents" => content_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![single_page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+ doc.trailer.set("Root", catalog_id);
+
+ doc
+ }
+
+ fn replace_text_in_tj_array_doc() -> Result<Document> {
+ // Content uses the TJ operator with a single-string array containing
+ // all 12 characters of "Hello World!".
+ let content = b"BT\n/F1 12 Tf\n100 700 Td\n[(Hello World!)] TJ\nET\n".to_vec();
+ let mut doc = build_doc_with_tj_array(content);
+ doc.replace_text(1, "Hello World!", "Modified text!", None)?;
+ Ok(doc)
+ }
+
+ #[test]
+ fn test_replace_text_in_tj_array_does_not_truncate() {
+ let doc = replace_text_in_tj_array_doc().unwrap();
+ let text = doc.extract_text(&[1]).unwrap();
+ assert_eq!(text, "Modified text! \n");
+ }
+
+ fn get_mut() -> Result<bool> {
+ let mut doc = Document::load("assets/example.pdf")?;
+ let arr = doc
+ .get_object_mut((5, 0))?
+ .as_dict_mut()?
+ .get_mut(b"Contents")?
+ .as_array_mut()?;
+ arr[0] = arr[0].clone();
+ Ok(true)
+ }
+
+ #[test]
+ fn test_get_mut() {
+ assert!(get_mut().unwrap());
+ }
+}
diff --git a/vendor/lopdf/tests/object_stream_comprehensive_test.rs b/vendor/lopdf/tests/object_stream_comprehensive_test.rs
new file mode 100644
index 000000000..90c9f3505
--- /dev/null
+++ b/vendor/lopdf/tests/object_stream_comprehensive_test.rs
@@ -0,0 +1,532 @@
+use lopdf::{Document, Object, ObjectStream, Stream, dictionary};
+
+#[test]
+fn test_can_be_compressed_stream_objects() {
+ let mut doc = Document::new();
+ let stream_id = doc.add_object(Stream::new(dictionary! { "Type" => "XObject" }, vec![1, 2, 3]));
+
+ let stream_obj = doc.objects.get(&stream_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(stream_id, stream_obj, &doc),
+ "Stream objects should not be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_non_zero_generation() {
+ let mut doc = Document::new();
+ let obj_id = (1, 5); // Non-zero generation
+ doc.objects.insert(obj_id, Object::Integer(42));
+
+ let obj = doc.objects.get(&obj_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(obj_id, obj, &doc),
+ "Objects with non-zero generation should not be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_trailer_referenced() {
+ let mut doc = Document::new();
+ let obj_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Test" => "Value"
+ }));
+
+ // Add to trailer (non-encryption reference)
+ doc.trailer.set("TestRef", obj_id);
+
+ let obj = doc.objects.get(&obj_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, obj, &doc),
+ "Non-encryption objects referenced in trailer should be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_xref_stream() {
+ let mut doc = Document::new();
+ let xref_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "XRef"
+ }));
+
+ let obj = doc.objects.get(&xref_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(xref_id, obj, &doc),
+ "XRef streams should not be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_objstm() {
+ let mut doc = Document::new();
+ let objstm_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "ObjStm"
+ }));
+
+ let obj = doc.objects.get(&objstm_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(objstm_id, obj, &doc),
+ "Object streams should not be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_catalog_non_linearized() {
+ let mut doc = Document::new();
+ let catalog_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ }));
+
+ let obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, obj, &doc),
+ "Catalog should be compressible in non-linearized PDFs"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_catalog_linearized() {
+ let mut doc = Document::new();
+
+ // Add linearization dictionary
+ let _lin_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Linearized" => 1
+ }));
+
+ let catalog_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ }));
+
+ let obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(catalog_id, obj, &doc),
+ "Catalog should not be compressible in linearized PDFs"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_pages() {
+ let mut doc = Document::new();
+ let pages_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference((3, 0))],
+ "Count" => 1
+ }));
+
+ let obj = doc.objects.get(&pages_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(pages_id, obj, &doc),
+ "Pages objects should be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_page() {
+ let mut doc = Document::new();
+ let page_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference((2, 0)),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ }));
+
+ let obj = doc.objects.get(&page_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(page_id, obj, &doc),
+ "Page objects should be compressible"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_encryption_dict() {
+ let mut doc = Document::new();
+ let encrypt_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Filter" => "Standard",
+ "V" => 1,
+ "R" => 2
+ }));
+
+ // Set as encryption dictionary
+ doc.trailer.set("Encrypt", encrypt_id);
+
+ let obj = doc.objects.get(&encrypt_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(encrypt_id, obj, &doc),
+ "Encryption dictionary should not be compressible"
+ );
+}
+
+#[test]
+fn test_catalog_can_be_compressed_with_trailer_reference() {
+ let mut doc = Document::with_version("1.5");
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ });
+
+ // Set as root in trailer (standard PDF structure)
+ doc.trailer.set("Root", catalog_id);
+
+ let catalog_obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, catalog_obj, &doc),
+ "Catalog should be compressible even when referenced in trailer"
+ );
+}
+
+#[test]
+fn test_info_dict_can_be_compressed_with_trailer_reference() {
+ let mut doc = Document::with_version("1.5");
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Test PDF",
+ "Author" => "Test Author",
+ "CreationDate" => "D:20250807120000Z"
+ });
+
+ // Set as info in trailer
+ doc.trailer.set("Info", info_id);
+
+ let info_obj = doc.objects.get(&info_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(info_id, info_obj, &doc),
+ "Info dictionary should be compressible even when referenced in trailer"
+ );
+}
+
+#[test]
+fn test_linearized_detection_via_catalog_compression() {
+ let mut doc = Document::new();
+
+ // Create catalog in non-linearized document
+ let catalog_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((2, 0))
+ }));
+
+ // Initially should be compressible (not linearized)
+ {
+ let obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, obj, &doc),
+ "Catalog should be compressible in non-linearized PDF"
+ );
+ }
+
+ // Add linearization dictionary
+ let _lin_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Linearized" => 1,
+ "L" => 12345,
+ "H" => vec![Object::Integer(100), Object::Integer(200)]
+ }));
+
+ // Now catalog should NOT be compressible
+ let obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(catalog_id, obj, &doc),
+ "Catalog should not be compressible after linearization"
+ );
+}
+
+#[test]
+fn test_can_be_compressed_regular_objects() {
+ let mut doc = Document::new();
+
+ // Test various regular object types that should be compressible
+ let int_id = doc.add_object(Object::Integer(42));
+ let bool_id = doc.add_object(Object::Boolean(true));
+ let string_id = doc.add_object(Object::String(b"Hello".to_vec(), lopdf::StringFormat::Literal));
+ let name_id = doc.add_object(Object::Name(b"Test".to_vec()));
+ let array_id = doc.add_object(Object::Array(vec![Object::Integer(1), Object::Integer(2)]));
+ let dict_id = doc.add_object(Object::Dictionary(dictionary! {
+ "Key" => "Value"
+ }));
+
+ // All should be compressible
+ assert!(ObjectStream::can_be_compressed(
+ int_id,
+ doc.objects.get(&int_id).unwrap(),
+ &doc
+ ));
+ assert!(ObjectStream::can_be_compressed(
+ bool_id,
+ doc.objects.get(&bool_id).unwrap(),
+ &doc
+ ));
+ assert!(ObjectStream::can_be_compressed(
+ string_id,
+ doc.objects.get(&string_id).unwrap(),
+ &doc
+ ));
+ assert!(ObjectStream::can_be_compressed(
+ name_id,
+ doc.objects.get(&name_id).unwrap(),
+ &doc
+ ));
+ assert!(ObjectStream::can_be_compressed(
+ array_id,
+ doc.objects.get(&array_id).unwrap(),
+ &doc
+ ));
+ assert!(ObjectStream::can_be_compressed(
+ dict_id,
+ doc.objects.get(&dict_id).unwrap(),
+ &doc
+ ));
+}
+
+#[test]
+fn test_save_with_object_streams_empty_document() {
+ let mut doc = Document::with_version("1.5");
+ doc.trailer.set("Root", Object::Reference((1, 0)));
+
+ let mut buffer = Vec::new();
+ let result = doc.save_modern(&mut buffer);
+ assert!(result.is_ok(), "Empty document should save successfully");
+}
+
+#[test]
+fn test_save_with_object_streams_single_page() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ let mut buffer = Vec::new();
+ let result = doc.save_modern(&mut buffer);
+ assert!(result.is_ok());
+
+ let content = String::from_utf8_lossy(&buffer);
+ assert!(
+ content.contains("/ObjStm"),
+ "Object streams should be created for single page PDF"
+ );
+}
+
+#[test]
+fn test_object_stream_builder_custom_config() {
+ let builder = ObjectStream::builder().max_objects(50).compression_level(9);
+
+ assert_eq!(builder.get_max_objects(), 50);
+ assert_eq!(builder.get_compression_level(), 9);
+
+ let _obj_stream = builder.build();
+ // Note: max_objects and compression_level are private fields
+ // We've already tested the builder getter methods above
+}
+
+#[test]
+fn test_object_stream_add_max_objects() {
+ let mut obj_stream = ObjectStream::builder().max_objects(3).build();
+
+ // Add objects up to max
+ assert!(obj_stream.add_object((1, 0), Object::Integer(1)).is_ok());
+ assert!(obj_stream.add_object((2, 0), Object::Integer(2)).is_ok());
+ assert!(obj_stream.add_object((3, 0), Object::Integer(3)).is_ok());
+
+ // Should fail when exceeding max
+ assert!(obj_stream.add_object((4, 0), Object::Integer(4)).is_err());
+}
+
+#[test]
+fn test_object_stream_invalid_generation() {
+ let mut obj_stream = ObjectStream::builder().build();
+
+ // Note: The current implementation doesn't validate generation in add_object
+ // It only checks during can_be_compressed. This test documents current behavior.
+ let result = obj_stream.add_object((1, 1), Object::Integer(42));
+ assert!(result.is_ok(), "add_object currently doesn't validate generation");
+}
+
+#[test]
+fn test_save_modern_with_mixed_objects() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Add various object types
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ });
+
+ let xobject_stream_id = doc.add_object(Stream::new(
+ dictionary! { "Type" => "XObject", "Subtype" => "Image" },
+ vec![0; 100],
+ ));
+
+ let annotation_id = doc.add_object(dictionary! {
+ "Type" => "Annot",
+ "Subtype" => "Text",
+ "Rect" => vec![100.into(), 100.into(), 200.into(), 200.into()]
+ });
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Annots" => vec![annotation_id.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ let mut buffer = Vec::new();
+ let result = doc.save_modern(&mut buffer);
+ assert!(result.is_ok());
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Verify object streams were created
+ assert!(content.contains("/ObjStm"));
+
+ // Verify stream objects are NOT in object streams
+ assert!(
+ content.contains(&format!("{} 0 obj", xobject_stream_id.0)),
+ "Stream objects should remain as top-level objects"
+ );
+
+ // Verify compressible objects are NOT present as individual objects
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Font", font_id.0)),
+ "Font object should be compressed"
+ );
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Annot", annotation_id.0)),
+ "Annotation object should be compressed"
+ );
+}
+
+#[test]
+fn test_parse_existing_object_stream() {
+ // Create a simple object stream content
+ let content = b"1 0 2 50 3 100\n\
+ <</Type/Font/Subtype/Type1/BaseFont/Helvetica>>\n\
+ <</Type/Annot/Subtype/Text/Rect[100 100 200 200]>>\n\
+ 42";
+
+ let stream = Stream::new(
+ dictionary! {
+ "Type" => "ObjStm",
+ "N" => 3,
+ "First" => 15
+ },
+ content.to_vec(),
+ );
+
+ let obj_stream = ObjectStream::new(&stream);
+ assert!(obj_stream.is_ok());
+
+ let obj_stream = obj_stream.unwrap();
+ assert_eq!(obj_stream.objects.len(), 3);
+ assert!(obj_stream.objects.contains_key(&(1, 0)));
+ assert!(obj_stream.objects.contains_key(&(2, 0)));
+ assert!(obj_stream.objects.contains_key(&(3, 0)));
+}
+
+#[test]
+fn test_regression_structural_objects_compression() {
+ // This test ensures the fix for structural object compression doesn't regress
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ // Set trailer reference
+ doc.trailer.set("Root", catalog_id);
+
+ // Verify objects can be compressed even after trailer reference
+ let catalog_obj = doc.objects.get(&catalog_id).unwrap();
+ let pages_obj = doc.objects.get(&pages_id).unwrap();
+ let page_obj = doc.objects.get(&page_id).unwrap();
+
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, catalog_obj, &doc),
+ "Catalog must be compressible in non-linearized PDFs even with trailer reference"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(pages_id, pages_obj, &doc),
+ "Pages object must be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(page_id, page_obj, &doc),
+ "Page object must be compressible"
+ );
+
+ // Save and verify compression
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Must have object streams
+ assert!(
+ content.contains("/ObjStm"),
+ "Object streams must be created when saving with modern format"
+ );
+
+ // All structural objects should be compressed now
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Catalog", catalog_id.0)),
+ "Catalog should be in object stream, not as individual object"
+ );
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Pages", pages_id.0)),
+ "Pages should be in object stream, not as individual object"
+ );
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Page", page_id.0)),
+ "Page should be in object stream, not as individual object"
+ );
+}
diff --git a/vendor/lopdf/tests/object_stream_edge_cases_test.rs b/vendor/lopdf/tests/object_stream_edge_cases_test.rs
new file mode 100644
index 000000000..aacac5a92
--- /dev/null
+++ b/vendor/lopdf/tests/object_stream_edge_cases_test.rs
@@ -0,0 +1,186 @@
+use lopdf::{Document, Object, ObjectStream, dictionary};
+
+#[test]
+fn test_empty_trailer() {
+ let doc = Document::with_version("1.5");
+ let obj_id = (1, 0);
+ let obj = Object::Dictionary(dictionary! { "Test" => "Value" });
+
+ // With empty trailer, all objects should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, &obj, &doc),
+ "Object should be compressible with empty trailer"
+ );
+}
+
+#[test]
+fn test_malformed_encrypt_reference() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj_id = doc.add_object(dictionary! {
+ "Type" => "Catalog"
+ });
+
+ // Set Encrypt to a malformed reference (wrong generation)
+ doc.trailer.set("Encrypt", Object::Reference((999, 99)));
+
+ // Object should still be compressible (not the encryption dict)
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, doc.objects.get(&obj_id).unwrap(), &doc),
+ "Object should be compressible even with malformed Encrypt reference"
+ );
+}
+
+#[test]
+fn test_self_referencing_object() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj_id = (5, 0);
+ doc.objects.insert(
+ obj_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Test",
+ "Self" => Object::Reference(obj_id) // Self reference
+ }),
+ );
+
+ doc.trailer.set("Test", obj_id);
+
+ // Should be compressible (not encryption dict)
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, doc.objects.get(&obj_id).unwrap(), &doc),
+ "Self-referencing object should be compressible"
+ );
+}
+
+#[test]
+fn test_circular_references() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj1_id = (1, 0);
+ let obj2_id = (2, 0);
+
+ doc.objects.insert(
+ obj1_id,
+ Object::Dictionary(dictionary! {
+ "Next" => Object::Reference(obj2_id)
+ }),
+ );
+
+ doc.objects.insert(
+ obj2_id,
+ Object::Dictionary(dictionary! {
+ "Next" => Object::Reference(obj1_id) // Circular reference
+ }),
+ );
+
+ doc.trailer.set("Start", obj1_id);
+
+ // Both should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(obj1_id, doc.objects.get(&obj1_id).unwrap(), &doc),
+ "First object in circular reference should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(obj2_id, doc.objects.get(&obj2_id).unwrap(), &doc),
+ "Second object in circular reference should be compressible"
+ );
+}
+
+#[test]
+fn test_trailer_with_all_pdf_types() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj_id = doc.add_object(dictionary! { "Type" => "Test" });
+
+ // Add all possible PDF types to trailer
+ doc.trailer.set("Root", obj_id);
+ doc.trailer.set("Null", Object::Null);
+ doc.trailer.set("Bool", Object::Boolean(true));
+ doc.trailer.set("Int", Object::Integer(42));
+ doc.trailer.set("Real", Object::Real(1.25));
+ doc.trailer
+ .set("String", Object::String(b"test".to_vec(), lopdf::StringFormat::Literal));
+ doc.trailer.set("Name", Object::Name(b"Test".to_vec()));
+ doc.trailer
+ .set("Array", Object::Array(vec![Object::Integer(1), Object::Integer(2)]));
+ doc.trailer
+ .set("Dict", Object::Dictionary(dictionary! { "Key" => "Value" }));
+
+ // Object should still be compressible
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, doc.objects.get(&obj_id).unwrap(), &doc),
+ "Object should be compressible with diverse trailer entries"
+ );
+}
+
+#[test]
+fn test_unicode_trailer_keys() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj_id = doc.add_object(dictionary! { "Test" => "Value" });
+
+ // Use Unicode/non-ASCII keys in trailer
+ doc.trailer.set("Root", obj_id);
+ doc.trailer.set(
+ "Ünïcödé",
+ Object::String(b"test".to_vec(), lopdf::StringFormat::Literal),
+ );
+ doc.trailer.set("日本語", Object::Integer(42));
+ doc.trailer.set("🎯", Object::Boolean(true));
+
+ // Should still work correctly
+ assert!(
+ ObjectStream::can_be_compressed(obj_id, doc.objects.get(&obj_id).unwrap(), &doc),
+ "Object should be compressible with Unicode trailer keys"
+ );
+}
+
+#[test]
+fn test_very_large_trailer() {
+ let mut doc = Document::with_version("1.5");
+
+ let obj_id = doc.add_object(dictionary! { "Type" => "Catalog" });
+
+ // Add many entries to trailer
+ doc.trailer.set("Root", obj_id);
+ for i in 0..1000 {
+ doc.trailer
+ .set(format!("Custom{:04}", i).as_bytes(), Object::Integer(i));
+ }
+
+ // Should still be efficient
+ let start = std::time::Instant::now();
+ let compressible = ObjectStream::can_be_compressed(obj_id, doc.objects.get(&obj_id).unwrap(), &doc);
+ let duration = start.elapsed();
+
+ assert!(compressible, "Object should be compressible even with large trailer");
+ assert!(
+ duration.as_micros() < 100,
+ "Check should be fast even with large trailer"
+ );
+}
+
+#[test]
+fn test_concurrent_modification_safety() {
+ // This test verifies the function doesn't panic with concurrent-like access patterns
+ let mut doc = Document::with_version("1.5");
+
+ let obj1_id = doc.add_object(dictionary! { "Type" => "Test1" });
+ let obj2_id = doc.add_object(dictionary! { "Type" => "Test2" });
+
+ doc.trailer.set("Ref1", obj1_id);
+
+ // Check first object
+ let result1 = ObjectStream::can_be_compressed(obj1_id, doc.objects.get(&obj1_id).unwrap(), &doc);
+
+ // Modify trailer between checks
+ doc.trailer.set("Ref2", obj2_id);
+ doc.trailer.set("Encrypt", obj1_id); // Now obj1 is encryption dict
+
+ // Check again - result should change
+ let result2 = ObjectStream::can_be_compressed(obj1_id, doc.objects.get(&obj1_id).unwrap(), &doc);
+
+ assert!(result1, "Initially should be compressible");
+ assert!(!result2, "Should not be compressible after becoming encryption dict");
+}
diff --git a/vendor/lopdf/tests/object_stream_methods_test.rs b/vendor/lopdf/tests/object_stream_methods_test.rs
new file mode 100644
index 000000000..1b497fa69
--- /dev/null
+++ b/vendor/lopdf/tests/object_stream_methods_test.rs
@@ -0,0 +1,482 @@
+use lopdf::{Document, Error, Object, ObjectStream, SaveOptions, Stream, dictionary};
+
+#[test]
+fn test_object_stream_parse_empty() {
+ let stream = Stream::new(
+ dictionary! {
+ "Type" => "ObjStm",
+ "N" => 0,
+ "First" => 0
+ },
+ vec![],
+ );
+
+ let obj_stream = ObjectStream::new(&stream).unwrap();
+ assert_eq!(obj_stream.objects.len(), 0);
+}
+
+#[test]
+fn test_object_stream_parse_preserves_encoded_content() {
+ let decoded = b"1 0 << /Kind /ArchiveEntry /Padding (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) >>";
+ let mut stream = Stream::new(
+ dictionary! {
+ "Type" => "ObjStm",
+ "N" => 1,
+ "First" => 4,
+ },
+ decoded.to_vec(),
+ );
+ stream.compress().unwrap();
+ let encoded = stream.content.clone();
+
+ let object_stream = ObjectStream::new_with_limit(&stream, Some(decoded.len())).unwrap();
+
+ assert!(object_stream.objects.contains_key(&(1, 0)));
+ assert_eq!(stream.content, encoded);
+ assert_eq!(stream.dict.get(b"Filter").unwrap().as_name().unwrap(), b"FlateDecode");
+}
+
+#[test]
+fn test_object_stream_parse_reports_unsupported_filters_without_mutating_input() {
+ let encoded = b"1 0 << >>".to_vec();
+ let stream = Stream::new(
+ dictionary! {
+ "Type" => "ObjStm",
+ "N" => 1,
+ "First" => 4,
+ "Filter" => "DCTDecode",
+ },
+ encoded.clone(),
+ );
+
+ let result = ObjectStream::new(&stream);
+
+ assert!(matches!(result, Err(Error::Unimplemented("decompression algorithms"))));
+ assert_eq!(stream.content, encoded);
+ assert_eq!(stream.dict.get(b"Filter").unwrap().as_name().unwrap(), b"DCTDecode");
+}
+
+#[test]
+fn test_object_stream_parse_with_empty_filter_array() {
+ let stream = Stream::new(
+ dictionary! {
+ "Type" => "ObjStm",
+ "N" => 1,
+ "First" => 4,
+ "Filter" => Object::Array(vec![]),
+ },
+ b"1 0 42".to_vec(),
+ );
+
+ let object_stream = ObjectStream::new(&stream).unwrap();
+
+ assert_eq!(object_stream.objects.get(&(1, 0)), Some(&Object::Integer(42)));
+}
+
+#[test]
+fn test_object_stream_config_default() {
+ let config = lopdf::ObjectStreamConfig::default();
+ assert_eq!(config.max_objects_per_stream, 100);
+ assert_eq!(config.compression_level, 6);
+}
+
+#[test]
+fn test_object_stream_to_stream_object() {
+ let mut obj_stream = ObjectStream::builder().build();
+
+ // Add some objects
+ obj_stream.add_object((1, 0), Object::Integer(42)).unwrap();
+ obj_stream.add_object((2, 0), Object::Boolean(true)).unwrap();
+ obj_stream.add_object((3, 0), Object::Name(b"Test".to_vec())).unwrap();
+
+ // Convert to stream object
+ let stream_obj = obj_stream.to_stream_object().unwrap();
+
+ // Verify stream properties
+ assert_eq!(stream_obj.dict.get(b"Type").unwrap(), &Object::Name(b"ObjStm".to_vec()));
+ assert_eq!(stream_obj.dict.get(b"N").unwrap(), &Object::Integer(3));
+ assert!(stream_obj.dict.has(b"First"));
+ assert!(stream_obj.dict.has(b"Length"));
+
+ // Verify content is not empty
+ assert!(!stream_obj.content.is_empty());
+}
+
+#[test]
+fn test_save_options_with_object_streams() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save with object streams enabled
+ let save_options = SaveOptions {
+ use_object_streams: true,
+ use_xref_streams: false,
+ linearize: false,
+ object_stream_config: Default::default(),
+ };
+
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, save_options).unwrap();
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Verify object streams were created
+ assert!(content.contains("/ObjStm"), "Object streams should be created");
+
+ // Verify PDF version is 1.5 or higher
+ assert!(
+ content.starts_with("%PDF-1.5") || content.starts_with("%PDF-1.6") || content.starts_with("%PDF-1.7"),
+ "PDF version should be 1.5 or higher for object streams"
+ );
+}
+
+#[test]
+fn test_save_options_without_object_streams() {
+ let mut doc = Document::with_version("1.4");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Save without object streams
+ let save_options = SaveOptions {
+ use_object_streams: false,
+ use_xref_streams: false,
+ linearize: false,
+ object_stream_config: Default::default(),
+ };
+
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, save_options).unwrap();
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Verify no object streams were created
+ assert!(!content.contains("/ObjStm"), "Object streams should not be created");
+
+ // Verify objects exist as individual objects
+ assert!(content.contains(&format!("{} 0 obj", catalog_id.0)));
+ assert!(content.contains(&format!("{} 0 obj", pages_id.0)));
+ assert!(content.contains(&format!("{} 0 obj", page_id.0)));
+}
+
+#[test]
+fn test_encrypted_document_object_streams() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Create encryption dictionary
+ let encrypt_id = doc.add_object(dictionary! {
+ "Filter" => "Standard",
+ "V" => 2,
+ "R" => 3,
+ "Length" => 128,
+ "P" => -1,
+ "O" => Object::String(vec![0; 32], lopdf::StringFormat::Hexadecimal),
+ "U" => Object::String(vec![0; 32], lopdf::StringFormat::Hexadecimal),
+ });
+
+ doc.trailer.set("Encrypt", encrypt_id);
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Verify encryption dictionary cannot be compressed
+ let encrypt_obj = doc.objects.get(&encrypt_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(encrypt_id, encrypt_obj, &doc),
+ "Encryption dictionary must not be compressible"
+ );
+
+ let mut buffer = Vec::new();
+ let result = doc.save_modern(&mut buffer);
+ assert!(result.is_ok());
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Encryption dictionary should remain as top-level object
+ assert!(
+ content.contains(&format!("{} 0 obj", encrypt_id.0)),
+ "Encryption dictionary must remain as individual object"
+ );
+}
+
+#[test]
+fn test_linearized_pdf_catalog_handling() {
+ let mut doc = Document::with_version("1.5");
+
+ // Add linearization parameters
+ let _lin_id = doc.add_object(dictionary! {
+ "Linearized" => 1,
+ "L" => 50000, // File length
+ "H" => vec![Object::Integer(1000), Object::Integer(2000)], // Hint stream location
+ "O" => 10, // First page object number
+ "E" => 5000, // End of first page
+ "N" => 1, // Number of pages
+ "T" => 45000 // First entry in main cross-reference table
+ });
+
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // In linearized PDF, catalog should not be compressible
+ let catalog_obj = doc.objects.get(&catalog_id).unwrap();
+ assert!(
+ !ObjectStream::can_be_compressed(catalog_id, catalog_obj, &doc),
+ "Catalog must not be compressible in linearized PDFs"
+ );
+
+ // But Pages and Page should still be compressible
+ let pages_obj = doc.objects.get(&pages_id).unwrap();
+ let page_obj = doc.objects.get(&page_id).unwrap();
+ assert!(
+ ObjectStream::can_be_compressed(pages_id, pages_obj, &doc),
+ "Pages should still be compressible in linearized PDFs"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(page_id, page_obj, &doc),
+ "Page should still be compressible in linearized PDFs"
+ );
+}
+
+#[test]
+fn test_object_stream_with_references() {
+ let mut obj_stream = ObjectStream::builder().build();
+
+ // Add objects with references
+ obj_stream
+ .add_object(
+ (1, 0),
+ Object::Dictionary(dictionary! {
+ "Type" => "Font",
+ "BaseFont" => "Helvetica",
+ "Encoding" => Object::Reference((5, 0)) // Reference to another object
+ }),
+ )
+ .unwrap();
+
+ obj_stream
+ .add_object(
+ (2, 0),
+ Object::Array(vec![
+ Object::Integer(100),
+ Object::Reference((10, 0)), // Reference
+ Object::String(b"Test".to_vec(), lopdf::StringFormat::Literal),
+ ]),
+ )
+ .unwrap();
+
+ let stream_obj = obj_stream.to_stream_object().unwrap();
+ assert_eq!(stream_obj.dict.get(b"N").unwrap(), &Object::Integer(2));
+
+ // Verify content contains the references
+ let content = String::from_utf8_lossy(&stream_obj.content);
+ assert!(content.contains("5 0 R")); // Reference syntax
+ assert!(content.contains("10 0 R"));
+}
+
+#[test]
+fn test_object_stream_with_nested_dictionaries() {
+ let mut obj_stream = ObjectStream::builder().build();
+
+ // Add complex nested dictionary
+ obj_stream
+ .add_object(
+ (1, 0),
+ Object::Dictionary(dictionary! {
+ "Type" => "ExtGState",
+ "CA" => 0.5,
+ "ca" => 0.5,
+ "BM" => Object::Array(vec![
+ Object::Name(b"Normal".to_vec()),
+ Object::Name(b"Multiply".to_vec())
+ ]),
+ "SMask" => dictionary! {
+ "Type" => "Mask",
+ "S" => "Alpha",
+ "G" => Object::Reference((10, 0))
+ }
+ }),
+ )
+ .unwrap();
+
+ let stream_obj = obj_stream.to_stream_object().unwrap();
+ assert!(!stream_obj.content.is_empty());
+}
+
+#[test]
+fn test_multiple_object_streams_in_document() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Add many objects to force multiple object streams
+ let mut page_ids = vec![];
+ for i in 0..250 {
+ // More than default max_objects_per_stream
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => Object::Reference((1000 + i, 0))
+ });
+ page_ids.push(page_id);
+ }
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => page_ids.into_iter().map(Object::Reference).collect::<Vec<_>>(),
+ "Count" => 250,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ let content = String::from_utf8_lossy(&buffer);
+
+ // Count object streams
+ let objstm_count = content.matches("/ObjStm").count();
+ assert!(
+ objstm_count >= 3,
+ "Should have multiple object streams for 250+ objects"
+ );
+}
+
+#[test]
+fn test_loads_catalog_from_later_generated_object_stream() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ // Fill the document with enough objects to force multiple object streams.
+ let max_objects_per_stream = lopdf::ObjectStreamConfig::default().max_objects_per_stream;
+ for _ in 0..=max_objects_per_stream {
+ doc.add_object(dictionary! {
+ "Dummy" => true,
+ });
+ }
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ let mut buffer = Vec::new();
+ doc.save_modern(&mut buffer).unwrap();
+
+ let content = String::from_utf8_lossy(&buffer);
+ let objstm_count = content.matches("/ObjStm").count();
+ assert!(objstm_count >= 2, "should have multiple object streams");
+
+ let loaded = Document::load_mem(&buffer).unwrap();
+ loaded
+ .catalog()
+ .expect("catalog should remain reachable from a later generated object stream");
+ assert_eq!(loaded.get_pages().len(), 1);
+}
diff --git a/vendor/lopdf/tests/object_stream_performance_test.rs b/vendor/lopdf/tests/object_stream_performance_test.rs
new file mode 100644
index 000000000..65265b18d
--- /dev/null
+++ b/vendor/lopdf/tests/object_stream_performance_test.rs
@@ -0,0 +1,166 @@
+use lopdf::{Document, Object, ObjectStream, SaveOptions, dictionary};
+use std::time::Instant;
+
+#[test]
+fn test_can_be_compressed_performance() {
+ // Create a document with many objects
+ let mut doc = Document::with_version("1.5");
+ let mut object_ids = Vec::new();
+
+ // Create 1000 objects
+ for i in 0..1000 {
+ let obj_id = doc.add_object(dictionary! {
+ "Type" => format!("TestObject{}", i),
+ "Index" => i as i64,
+ "Data" => format!("This is test object number {}", i)
+ });
+ object_ids.push(obj_id);
+ }
+
+ // Add some to trailer
+ doc.trailer.set("Root", object_ids[0]);
+ doc.trailer.set("Info", object_ids[1]);
+ doc.trailer.set("Custom1", object_ids[2]);
+ doc.trailer.set("Custom2", object_ids[3]);
+
+ // Measure performance of can_be_compressed checks
+ let start = Instant::now();
+ let mut compressible_count = 0;
+
+ for &id in &object_ids {
+ if let Some(obj) = doc.objects.get(&id)
+ && ObjectStream::can_be_compressed(id, obj, &doc)
+ {
+ compressible_count += 1;
+ }
+ }
+
+ let duration = start.elapsed();
+
+ println!("Checked {} objects in {:?}", object_ids.len(), duration);
+ println!("Compressible objects: {}", compressible_count);
+
+ // All objects should be compressible (none are encryption dicts)
+ assert_eq!(
+ compressible_count,
+ object_ids.len(),
+ "All non-encryption objects should be compressible"
+ );
+
+ // Performance check: should complete in reasonable time
+ assert!(
+ duration.as_millis() < 100,
+ "Performance check took too long: {:?}",
+ duration
+ );
+}
+
+#[test]
+fn test_save_performance_with_trailer_objects() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ // Create many pages
+ let mut page_ids = Vec::new();
+ for i in 0..100 {
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => Object::Reference((1000 + i, 0))
+ });
+ page_ids.push(page_id);
+ }
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => page_ids.iter().map(|&id| Object::Reference(id)).collect::<Vec<_>>(),
+ "Count" => page_ids.len() as i64
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Performance Test PDF",
+ "PageCount" => page_ids.len() as i64
+ });
+
+ // Add many custom entries to trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+ for i in 0..10 {
+ doc.trailer.set(format!("Custom{}", i).as_bytes(), Object::Integer(i));
+ }
+
+ // Measure save performance
+ let options = SaveOptions::builder().use_object_streams(true).build();
+
+ let start = Instant::now();
+ let mut output = Vec::new();
+ doc.save_with_options(&mut output, options).unwrap();
+ let save_duration = start.elapsed();
+
+ println!("Saved {} page PDF in {:?}", page_ids.len(), save_duration);
+ println!("Output size: {} bytes", output.len());
+
+ // Should complete quickly even with many objects
+ assert!(
+ save_duration.as_millis() < 500,
+ "Save took too long: {:?}",
+ save_duration
+ );
+
+ // Verify compression worked
+ let content = String::from_utf8_lossy(&output);
+ assert!(content.contains("/ObjStm"), "Object streams should be created");
+}
+
+#[test]
+fn test_encryption_check_performance() {
+ // Test the specific encryption dictionary check performance
+ let mut doc = Document::with_version("1.5");
+
+ // Create an encryption dictionary
+ let encrypt_id = doc.add_object(dictionary! {
+ "Filter" => "Standard",
+ "V" => 2
+ });
+
+ // Set it in trailer
+ doc.trailer.set("Encrypt", encrypt_id);
+
+ // Create many other objects
+ let mut other_ids = Vec::new();
+ for i in 0..1000 {
+ let id = doc.add_object(Object::Integer(i));
+ other_ids.push(id);
+ }
+
+ // Time the encryption check
+ let start = Instant::now();
+
+ // Check encryption dictionary
+ let encrypt_obj = doc.objects.get(&encrypt_id).unwrap();
+ let encrypt_compressible = ObjectStream::can_be_compressed(encrypt_id, encrypt_obj, &doc);
+
+ // Check many non-encryption objects
+ for &id in &other_ids[..100] {
+ // Check first 100
+ if let Some(obj) = doc.objects.get(&id) {
+ let _ = ObjectStream::can_be_compressed(id, obj, &doc);
+ }
+ }
+
+ let duration = start.elapsed();
+
+ println!("Encryption check performance: {:?} for 101 objects", duration);
+
+ assert!(!encrypt_compressible, "Encryption dict should not be compressible");
+ assert!(duration.as_micros() < 1000, "Check should be very fast");
+}
diff --git a/vendor/lopdf/tests/page_content.rs b/vendor/lopdf/tests/page_content.rs
new file mode 100644
index 000000000..f0b770d90
--- /dev/null
+++ b/vendor/lopdf/tests/page_content.rs
@@ -0,0 +1,45 @@
+use lopdf::{Document, Stream, content::Content, dictionary};
+
+#[test]
+fn get_page_content_separates_streams_at_token_boundary() {
+ let mut doc = Document::with_version("1.5");
+ // Producer writes stream that ends without trailing whitespace
+ let s1 = doc.add_object(Stream::new(dictionary! {}, b"1 0 0 1 50".to_vec()));
+ let s2 = doc.add_object(Stream::new(dictionary! {}, b"100 cm".to_vec()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Contents" => vec![s1.into(), s2.into()],
+ });
+
+ let bytes = doc.get_page_content(page_id);
+ let content = Content::decode(&bytes).unwrap();
+
+ assert_eq!(content.operations.len(), 1);
+ let op = &content.operations[0];
+ assert_eq!(op.operator, "cm");
+ let operands: Vec<f32> = op.operands.iter().map(|o| o.as_float().unwrap()).collect();
+
+ assert_eq!(operands, [1.0, 0.0, 0.0, 1.0, 50.0, 100.0]);
+}
+
+#[test]
+fn get_page_content_terminates_trailing_comment() {
+ let mut doc = Document::with_version("1.5");
+ // Producer writes stream that ends with a comment without EOL
+ let s1 = doc.add_object(Stream::new(dictionary! {}, b"% a comment".to_vec()));
+ let s2 = doc.add_object(Stream::new(dictionary! {}, b"1 0 0 1 50 100 cm".to_vec()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Contents" => vec![s1.into(), s2.into()],
+ });
+
+ let bytes = doc.get_page_content(page_id);
+ let content = Content::decode(&bytes).unwrap();
+
+ assert_eq!(content.operations.len(), 1);
+ let op = &content.operations[0];
+ assert_eq!(op.operator, "cm");
+ let operands: Vec<f32> = op.operands.iter().map(|o| o.as_float().unwrap()).collect();
+
+ assert_eq!(operands, [1.0, 0.0, 0.0, 1.0, 50.0, 100.0]);
+}
diff --git a/vendor/lopdf/tests/save_options_xref_streams_test.rs b/vendor/lopdf/tests/save_options_xref_streams_test.rs
new file mode 100644
index 000000000..913fd8469
--- /dev/null
+++ b/vendor/lopdf/tests/save_options_xref_streams_test.rs
@@ -0,0 +1,128 @@
+//! `SaveOptions::use_xref_streams` on its own, without object streams.
+//!
+//! The two features are independent in the PDF specification, so asking for a
+//! cross-reference stream should not require asking for object streams as well.
+
+#![cfg(not(feature = "async"))]
+
+use lopdf::xref::XrefType;
+use lopdf::{Document, Object, SaveOptions, Stream, dictionary};
+
+/// A one page document written with a classic cross-reference table, as a document
+/// loaded from a pre-1.5 file would be.
+fn sample_document() -> Document {
+ let mut doc = Document::with_version("1.4");
+ doc.reference_table.cross_reference_type = XrefType::CrossReferenceTable;
+
+ let pages_id = doc.new_object_id();
+ let content_id = doc.add_object(Stream::new(dictionary! {}, b"BT ET".to_vec()));
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => Object::Reference(pages_id),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => Object::Reference(content_id),
+ });
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![Object::Reference(page_id)],
+ "Count" => 1,
+ }),
+ );
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference(pages_id),
+ });
+ doc.trailer.set("Root", Object::Reference(catalog_id));
+
+ doc
+}
+
+fn contains(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|window| window == needle)
+}
+
+#[test]
+fn xref_streams_are_written_without_object_streams() {
+ let mut doc = sample_document();
+
+ let options = SaveOptions::builder()
+ .use_object_streams(false)
+ .use_xref_streams(true)
+ .build();
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ assert!(
+ contains(&buffer, b"/Type/XRef") || contains(&buffer, b"/Type /XRef"),
+ "a requested cross-reference stream should be written even with object streams off"
+ );
+ assert!(
+ !contains(&buffer, b"\nxref\n"),
+ "the classic cross-reference table should not be written as well"
+ );
+ assert!(
+ !contains(&buffer, b"/ObjStm"),
+ "object streams were not requested and must not appear"
+ );
+
+ // A cross-reference stream is a PDF 1.5 construct, so the header has to say so.
+ assert!(
+ buffer.starts_with(b"%PDF-1.5"),
+ "expected the version to be raised to 1.5, got {:?}",
+ String::from_utf8_lossy(&buffer[..8.min(buffer.len())])
+ );
+
+ let reloaded = Document::load_mem(&buffer).unwrap();
+ assert_eq!(reloaded.get_pages().len(), 1, "the saved document should still load");
+}
+
+#[test]
+fn cross_reference_table_is_kept_when_xref_streams_are_not_requested() {
+ let mut doc = sample_document();
+
+ let options = SaveOptions::builder()
+ .use_object_streams(false)
+ .use_xref_streams(false)
+ .build();
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ assert!(
+ contains(&buffer, b"\nxref\n"),
+ "without the option the document keeps its cross-reference table"
+ );
+ assert!(
+ !contains(&buffer, b"/Type/XRef") && !contains(&buffer, b"/Type /XRef"),
+ "no cross-reference stream should appear when it was not requested"
+ );
+ assert!(
+ buffer.starts_with(b"%PDF-1.4"),
+ "the version should be left alone when no 1.5 feature is used"
+ );
+}
+
+#[test]
+fn both_options_together_still_write_object_and_xref_streams() {
+ let mut doc = sample_document();
+
+ let options = SaveOptions::builder()
+ .use_object_streams(true)
+ .use_xref_streams(true)
+ .build();
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ assert!(
+ contains(&buffer, b"/ObjStm"),
+ "object streams were requested and should still be written"
+ );
+ assert!(
+ contains(&buffer, b"/Type/XRef") || contains(&buffer, b"/Type /XRef"),
+ "cross-reference streams were requested and should still be written"
+ );
+
+ let reloaded = Document::load_mem(&buffer).unwrap();
+ assert_eq!(reloaded.get_pages().len(), 1, "the saved document should still load");
+}
diff --git a/vendor/lopdf/tests/simple_object_stream_test.rs b/vendor/lopdf/tests/simple_object_stream_test.rs
new file mode 100644
index 000000000..01d7e1ea2
--- /dev/null
+++ b/vendor/lopdf/tests/simple_object_stream_test.rs
@@ -0,0 +1,168 @@
+use lopdf::{Document, Object, ObjectId, ObjectStream, Stream, dictionary};
+
+#[test]
+fn test_object_stream_builder() {
+ let builder = ObjectStream::builder();
+ assert_eq!(builder.get_max_objects(), 100);
+ assert_eq!(builder.get_compression_level(), 6);
+}
+
+#[test]
+fn test_object_stream_add_and_build() {
+ let mut obj_stream = ObjectStream::builder().build();
+
+ // Add some objects
+ obj_stream.add_object((1, 0), Object::Integer(42)).unwrap();
+ obj_stream.add_object((2, 0), Object::Boolean(true)).unwrap();
+ obj_stream.add_object((3, 0), Object::Name(b"Test".to_vec())).unwrap();
+
+ // Build the stream content
+ let content = obj_stream.build_stream_content().unwrap();
+ assert!(!content.is_empty());
+
+ // Convert to stream object
+ let stream_obj = obj_stream.to_stream_object().unwrap();
+ assert_eq!(stream_obj.dict.get(b"Type").unwrap(), &Object::Name(b"ObjStm".to_vec()));
+ assert_eq!(stream_obj.dict.get(b"N").unwrap(), &Object::Integer(3));
+}
+
+#[test]
+fn test_save_with_object_streams() {
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type1",
+ "BaseFont" => "Helvetica"
+ });
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+
+ let content = lopdf::content::Content {
+ operations: vec![
+ lopdf::content::Operation::new("BT", vec![]),
+ lopdf::content::Operation::new("Tf", vec!["F1".into(), 12.into()]),
+ lopdf::content::Operation::new("Td", vec![50.into(), 700.into()]),
+ lopdf::content::Operation::new("Tj", vec![Object::string_literal("Test Document")]),
+ lopdf::content::Operation::new("ET", vec![]),
+ ],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+
+ // Test save_modern
+ let mut buffer = Vec::new();
+ let result = doc.save_modern(&mut buffer);
+ assert!(result.is_ok());
+
+ // Verify PDF was created
+ let content = String::from_utf8_lossy(&buffer);
+ assert!(content.starts_with("%PDF-1.5"));
+
+ // Verify object streams were created
+ assert!(content.contains("/ObjStm"), "Object streams should be created");
+
+ // Verify that structural objects are NOT present as individual objects
+ assert!(
+ !content.contains("2 0 obj\n<</Type/Pages"),
+ "Pages object should be compressed"
+ );
+ assert!(
+ !content.contains("3 0 obj\n<</Type/Page"),
+ "Page object should be compressed"
+ );
+}
+
+/// Construct a raw ObjStm whose embedded objects are preceded by newlines
+/// (as seen in real PDFs like MAECI documents). Without the whitespace-
+/// skipping fix in ObjectStream::new, all objects would silently fail to
+/// parse and the returned ObjectStream would be empty.
+#[test]
+fn test_object_stream_parses_objects_with_leading_whitespace() {
+ // Build the object data portion: two dictionaries preceded by \n
+ // Object 10: a Font dictionary
+ // Object 11: a FontDescriptor dictionary
+ let obj10_bytes = b"\n<< /Type /Font /Subtype /TrueType /BaseFont /Calibri >>";
+ let obj11_bytes = b"\n<< /Type /FontDescriptor /FontName /Calibri >>";
+
+ let obj10_offset = 0usize;
+ let obj11_offset = obj10_bytes.len();
+
+ // Build the index block: "obj_num offset obj_num offset "
+ let index = format!("10 {} 11 {} ", obj10_offset, obj11_offset);
+ let first_offset = index.len();
+
+ // Assemble the full stream content: index block + object data
+ let mut content = Vec::new();
+ content.extend_from_slice(index.as_bytes());
+ content.extend_from_slice(obj10_bytes);
+ content.extend_from_slice(obj11_bytes);
+
+ let dict = dictionary! {
+ "Type" => "ObjStm",
+ "N" => 2,
+ "First" => first_offset as i64,
+ };
+
+ let stream = Stream::new(dict, content);
+ let obj_stream = ObjectStream::new(&stream).expect("should parse object stream");
+
+ // Both objects must be present
+ assert_eq!(
+ obj_stream.objects.len(),
+ 2,
+ "expected 2 objects but got {}; leading whitespace was not skipped",
+ obj_stream.objects.len()
+ );
+
+ // Verify object 10 is a Font dictionary
+ let obj10 = obj_stream
+ .objects
+ .get(&(10u32, 0u16) as &ObjectId)
+ .expect("object 10 missing");
+ if let Object::Dictionary(dict) = obj10 {
+ assert_eq!(dict.get(b"BaseFont").unwrap().as_name().unwrap(), b"Calibri");
+ } else {
+ panic!("object 10 should be a Dictionary, got {:?}", obj10);
+ }
+
+ // Verify object 11 is a FontDescriptor dictionary
+ let obj11 = obj_stream
+ .objects
+ .get(&(11u32, 0u16) as &ObjectId)
+ .expect("object 11 missing");
+ if let Object::Dictionary(dict) = obj11 {
+ assert_eq!(dict.get(b"FontName").unwrap().as_name().unwrap(), b"Calibri");
+ } else {
+ panic!("object 11 should be a Dictionary, got {:?}", obj11);
+ }
+}
diff --git a/vendor/lopdf/tests/stream_length_recovery.rs b/vendor/lopdf/tests/stream_length_recovery.rs
new file mode 100644
index 000000000..6ae4c3d19
--- /dev/null
+++ b/vendor/lopdf/tests/stream_length_recovery.rs
@@ -0,0 +1,306 @@
+use std::collections::HashMap;
+
+use lopdf::{Document, LoadOptions, Object};
+
+fn pdf_with_stream(declared_length: usize, content: &[u8], trailer: &[u8]) -> Vec<u8> {
+ let mut pdf = Vec::new();
+ let mut offsets = Vec::new();
+
+ pdf.extend_from_slice(b"%PDF-1.7\n");
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(
+ b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Resources << /XObject << /Im0 4 0 R >> >> >>\nendobj\n",
+ );
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(
+ format!(
+ "4 0 obj\n<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceRGB \
+ /BitsPerComponent 8 /Filter [/FlateDecode /DCTDecode] /Length {declared_length} >>\nstream\n"
+ )
+ .as_bytes(),
+ );
+ pdf.extend_from_slice(content);
+ pdf.extend_from_slice(trailer);
+
+ let xref_offset = pdf.len();
+ pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f \n");
+ for offset in offsets {
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes());
+ pdf
+}
+
+#[test]
+fn lenient_load_recovers_an_unambiguous_stream_length_mismatch() {
+ let content = b"actual stream bytes";
+ let pdf = pdf_with_stream(0, content, b"\nendstream\nendobj\n");
+
+ let document = Document::load_mem(&pdf).unwrap();
+ let Object::Stream(stream) = document.get_object((4, 0)).unwrap() else {
+ panic!("recovered object must remain a stream");
+ };
+ assert_eq!(stream.content, content);
+ assert_eq!(
+ stream.dict.get(b"Length").unwrap().as_i64().unwrap(),
+ content.len() as i64
+ );
+}
+
+#[test]
+fn strict_load_rejects_a_stream_length_mismatch() {
+ let content = b"actual stream bytes";
+ let malformed = pdf_with_stream(0, content, b"\nendstream\nendobj\n");
+ let conforming = pdf_with_stream(content.len(), content, b"\nendstream\nendobj\n");
+ let strict = LoadOptions {
+ strict: true,
+ ..Default::default()
+ };
+
+ assert!(Document::load_mem_with_options(&conforming, strict.clone()).is_ok());
+ assert!(Document::load_mem_with_options(&malformed, strict).is_err());
+}
+
+#[test]
+fn lenient_load_does_not_guess_an_ambiguous_stream_boundary() {
+ let pdf = pdf_with_stream(
+ 0,
+ b"first candidate\nendstream\nendobj\nbytes after the false boundary",
+ b"\nendstream\nendobj\n",
+ );
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((4, 0)).is_err());
+}
+
+#[test]
+fn lenient_load_does_not_recover_without_endstream() {
+ let pdf = pdf_with_stream(0, b"unterminated stream bytes", b"\nendobj\n");
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((4, 0)).is_err());
+}
+
+/// Assemble a PDF from whole `"<id> 0 obj ... endobj"` blobs laid out in the
+/// given order. `xref_overrides` lets tests record an offset that differs from
+/// the physical one; the returned map holds the true physical offsets.
+fn pdf_from_objects(objects: &[(u32, &[u8])], xref_overrides: &[(u32, usize)]) -> (Vec<u8>, HashMap<u32, usize>) {
+ let mut pdf = Vec::new();
+ let mut physical = HashMap::new();
+
+ pdf.extend_from_slice(b"%PDF-1.7\n");
+ for (id, body) in objects {
+ physical.insert(*id, pdf.len());
+ pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
+ pdf.extend_from_slice(body);
+ pdf.extend_from_slice(b"endobj\n");
+ }
+
+ let xref_offset = pdf.len();
+ let size = objects.iter().map(|(id, _)| *id).max().unwrap_or(0) + 1;
+ pdf.extend_from_slice(b"xref\n");
+ pdf.extend_from_slice(format!("0 {size}\n0000000000 65535 f \n").as_bytes());
+ for object_number in 1..size {
+ let offset = xref_overrides
+ .iter()
+ .find(|&&(id, _)| id == object_number)
+ .map(|&(_, offset)| offset)
+ .or_else(|| physical.get(&object_number).copied())
+ .expect("xref entry missing for object");
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(
+ format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes(),
+ );
+ (pdf, physical)
+}
+
+fn catalog() -> &'static [u8] {
+ b"<< /Type /Catalog /Pages 2 0 R >>\n"
+}
+
+fn pages(kids: &str) -> Vec<u8> {
+ format!("<< /Type /Pages /Kids [{kids}] /Count 1 >>\n").into_bytes()
+}
+
+fn page(xobjects: &str) -> Vec<u8> {
+ format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Resources << /XObject << {xobjects} >> >> >>\n")
+ .into_bytes()
+}
+
+/// Body of an image stream object with a *correct* `/Length`, ending right
+/// before the `endobj` keyword appended by `pdf_from_objects`.
+fn image_stream_body(content: &[u8]) -> Vec<u8> {
+ let mut body = format!(
+ "<< /Type /XObject /Subtype /Image /Width {} /Height 1 /ColorSpace /DeviceRGB \
+ /BitsPerComponent 8 /Length {} >>\nstream\n",
+ content.len() / 3,
+ content.len()
+ )
+ .into_bytes();
+ body.extend_from_slice(content);
+ body.extend_from_slice(b"\nendstream\n");
+ body
+}
+
+#[test]
+fn accurate_but_out_of_order_xref_offsets_load_every_object() {
+ // Physical order: catalog, pages, image stream, page. The xref rows are
+ // still emitted in ascending object-number order, so the recorded offsets
+ // do not increase in file order.
+ let content = vec![b'A'; 48];
+ let objects: Vec<(u32, Vec<u8>)> = vec![
+ (1, catalog().to_vec()),
+ (2, pages("3 0 R")),
+ (4, image_stream_body(&content)),
+ (3, page("/Im0 4 0 R")),
+ ];
+ let bodies: Vec<(u32, &[u8])> = objects.iter().map(|(id, body)| (*id, body.as_slice())).collect();
+ let (pdf, _) = pdf_from_objects(&bodies, &[]);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((1, 0)).is_ok());
+ assert!(document.get_object((2, 0)).is_ok());
+ assert!(document.get_object((3, 0)).is_ok());
+ let Object::Stream(stream) = document.get_object((4, 0)).unwrap() else {
+ panic!("image object must remain a stream");
+ };
+ assert_eq!(stream.content, content);
+}
+
+/// Byte position just after the only `stream` keyword's EOL in the document.
+fn stream_data_start(pdf: &[u8]) -> usize {
+ pdf.windows(7)
+ .position(|window| window == b"stream\n")
+ .expect("no stream keyword")
+ + 7
+}
+
+#[test]
+fn inaccurate_xref_offset_inside_a_stream_only_loses_the_mislocated_object() {
+ // Object 5 physically follows object 4, but its xref offset is miswritten
+ // to point into object 4's stream payload. Object 4 itself is well-formed
+ // (its /Length is correct), so it still loads; only the mislocated object
+ // is lost.
+ let content = vec![b'A'; 48];
+ let objects: Vec<(u32, Vec<u8>)> = vec![
+ (1, catalog().to_vec()),
+ (2, pages("3 0 R")),
+ (3, page("/Im0 4 0 R /F1 5 0 R")),
+ (4, image_stream_body(&content)),
+ (5, b"<< /Type /Font >>\n".to_vec()),
+ ];
+ let bodies: Vec<(u32, &[u8])> = objects.iter().map(|(id, body)| (*id, body.as_slice())).collect();
+ let (pdf, _) = pdf_from_objects(&bodies, &[]);
+ let false_offset = stream_data_start(&pdf) + 16;
+ let (pdf, _) = pdf_from_objects(&bodies, &[(5, false_offset)]);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((1, 0)).is_ok());
+ assert!(document.get_object((2, 0)).is_ok());
+ assert!(document.get_object((3, 0)).is_ok());
+ let Object::Stream(stream) = document.get_object((4, 0)).unwrap() else {
+ panic!("image object must remain a stream");
+ };
+ assert_eq!(stream.content, content);
+ assert!(document.get_object((5, 0)).is_err());
+}
+
+#[test]
+fn strict_mode_aborts_when_an_xref_offset_is_unparseable() {
+ // Strict mode fails the whole load when any object cannot be parsed —
+ // here object 5, whose xref offset points into object 4's payload.
+ // Object 4 itself survives parsing; the abort is caused solely by the
+ // unparseable neighbor offset.
+ let content = vec![b'A'; 48];
+ let objects: Vec<(u32, Vec<u8>)> = vec![
+ (1, catalog().to_vec()),
+ (2, pages("3 0 R")),
+ (3, page("/Im0 4 0 R")),
+ (4, image_stream_body(&content)),
+ (5, b"<< /Type /Font >>\n".to_vec()),
+ ];
+ let bodies: Vec<(u32, &[u8])> = objects.iter().map(|(id, body)| (*id, body.as_slice())).collect();
+ let (pdf, _) = pdf_from_objects(&bodies, &[]);
+ let false_offset = stream_data_start(&pdf) + 16;
+ let (pdf, _) = pdf_from_objects(&bodies, &[(5, false_offset)]);
+ let strict = LoadOptions {
+ strict: true,
+ ..Default::default()
+ };
+
+ assert!(Document::load_mem_with_options(&pdf, strict).is_err());
+}
+
+#[test]
+fn out_of_order_xref_with_offset_inside_a_stream_only_loses_the_mislocated_object() {
+ // Object 3 physically sits after the image stream of object 4, but its
+ // recorded xref offset lands inside object 4's payload. Object 4 parses
+ // fine; only the mislocated object disappears.
+ let content = vec![b'A'; 48];
+ let objects: Vec<(u32, Vec<u8>)> = vec![
+ (1, catalog().to_vec()),
+ (2, pages("3 0 R")),
+ (4, image_stream_body(&content)),
+ (3, page("/Im0 4 0 R")),
+ ];
+ let bodies: Vec<(u32, &[u8])> = objects.iter().map(|(id, body)| (*id, body.as_slice())).collect();
+ let (pdf, _) = pdf_from_objects(&bodies, &[]);
+ let false_offset = stream_data_start(&pdf) + 16;
+ let (pdf, _) = pdf_from_objects(&bodies, &[(3, false_offset)]);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((1, 0)).is_ok());
+ assert!(document.get_object((2, 0)).is_ok());
+ assert!(document.get_object((3, 0)).is_err());
+ let Object::Stream(stream) = document.get_object((4, 0)).unwrap() else {
+ panic!("image object must remain a stream");
+ };
+ assert_eq!(stream.content, content);
+}
+
+/// Body of a stream whose declared `/Length` is deliberately wrong (too
+/// small), so loading has to rely on boundary recovery.
+fn wrong_length_stream_body(content: &[u8]) -> Vec<u8> {
+ let mut body = format!(
+ "<< /Type /XObject /Subtype /Image /Width {} /Height 1 /ColorSpace /DeviceRGB \
+ /BitsPerComponent 8 /Length 0 >>\nstream\n",
+ content.len() / 3
+ )
+ .into_bytes();
+ body.extend_from_slice(content);
+ body.extend_from_slice(b"\nendstream\n");
+ body
+}
+
+#[test]
+fn stream_length_recovery_stops_at_the_next_recorded_xref_offset() {
+ // A stream with a wrong /Length can only be recovered if its unambiguous
+ // `endstream` lies before the next recorded xref offset: recovery must
+ // not cross into a neighboring object even when that offset is itself
+ // inaccurate. Here object 5's offset points into object 4's payload, so
+ // the recovery window ends mid-data and object 4 is dropped.
+ let content = vec![b'A'; 48];
+ let objects: Vec<(u32, Vec<u8>)> = vec![
+ (1, catalog().to_vec()),
+ (2, pages("3 0 R")),
+ (3, page("/Im0 4 0 R")),
+ (4, wrong_length_stream_body(&content)),
+ (5, b"<< /Type /Font >>\n".to_vec()),
+ ];
+ let bodies: Vec<(u32, &[u8])> = objects.iter().map(|(id, body)| (*id, body.as_slice())).collect();
+ let (pdf, _) = pdf_from_objects(&bodies, &[]);
+ let false_offset = stream_data_start(&pdf) + 16;
+ let (pdf, _) = pdf_from_objects(&bodies, &[(5, false_offset)]);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert!(document.get_object((1, 0)).is_ok());
+ assert!(document.get_object((2, 0)).is_ok());
+ assert!(document.get_object((3, 0)).is_ok());
+ assert!(document.get_object((4, 0)).is_err());
+ assert!(document.get_object((5, 0)).is_err());
+}
diff --git a/vendor/lopdf/tests/trailer_reference_compression_test.rs b/vendor/lopdf/tests/trailer_reference_compression_test.rs
new file mode 100644
index 000000000..3e5549cc1
--- /dev/null
+++ b/vendor/lopdf/tests/trailer_reference_compression_test.rs
@@ -0,0 +1,360 @@
+use lopdf::{Document, Object, ObjectStream, dictionary};
+
+#[test]
+fn test_multiple_trailer_references_all_compressible() {
+ let mut doc = Document::with_version("1.5");
+
+ // Create multiple objects that will be referenced in trailer
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((10, 0))
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Test",
+ "Author" => "Test Author"
+ });
+
+ let metadata_id = doc.add_object(dictionary! {
+ "Type" => "Metadata",
+ "Subtype" => "XML"
+ });
+
+ let outlines_id = doc.add_object(dictionary! {
+ "Type" => "Outlines",
+ "Count" => 0
+ });
+
+ // Add all to trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+ doc.trailer.set("Metadata", metadata_id);
+ doc.trailer.set("Outlines", outlines_id);
+
+ // All should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(info_id, doc.objects.get(&info_id).unwrap(), &doc),
+ "Info should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(metadata_id, doc.objects.get(&metadata_id).unwrap(), &doc),
+ "Metadata should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(outlines_id, doc.objects.get(&outlines_id).unwrap(), &doc),
+ "Outlines should be compressible"
+ );
+}
+
+#[test]
+fn test_encryption_dict_with_other_trailer_refs() {
+ let mut doc = Document::with_version("1.5");
+
+ // Create catalog and encryption dictionary
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => Object::Reference((10, 0))
+ });
+
+ let encrypt_id = doc.add_object(dictionary! {
+ "Filter" => "Standard",
+ "V" => 2,
+ "R" => 3,
+ "Length" => 128
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Encrypted PDF"
+ });
+
+ // Add to trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Encrypt", encrypt_id);
+ doc.trailer.set("Info", info_id);
+
+ // Catalog and Info should be compressible, Encrypt should not
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should be compressible even with encryption"
+ );
+ assert!(
+ !ObjectStream::can_be_compressed(encrypt_id, doc.objects.get(&encrypt_id).unwrap(), &doc),
+ "Encryption dictionary should NOT be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(info_id, doc.objects.get(&info_id).unwrap(), &doc),
+ "Info should be compressible even with encryption"
+ );
+}
+
+#[test]
+fn test_trailer_with_non_reference_values() {
+ let mut doc = Document::with_version("1.5");
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog"
+ });
+
+ // Add various types to trailer
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Size", Object::Integer(100));
+ doc.trailer.set("Prev", Object::Integer(1234));
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(vec![1, 2, 3, 4], lopdf::StringFormat::Hexadecimal),
+ Object::String(vec![5, 6, 7, 8], lopdf::StringFormat::Hexadecimal),
+ ]),
+ );
+
+ // Catalog should still be compressible
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should be compressible with non-reference trailer entries"
+ );
+}
+
+#[test]
+fn test_same_object_referenced_multiple_times() {
+ let mut doc = Document::with_version("1.5");
+
+ let shared_dict_id = doc.add_object(dictionary! {
+ "Shared" => "Dictionary"
+ });
+
+ // Reference the same object from multiple trailer keys
+ doc.trailer.set("Custom1", shared_dict_id);
+ doc.trailer.set("Custom2", shared_dict_id);
+ doc.trailer.set("Custom3", shared_dict_id);
+
+ // Should still be compressible (not encryption dict)
+ assert!(
+ ObjectStream::can_be_compressed(shared_dict_id, doc.objects.get(&shared_dict_id).unwrap(), &doc),
+ "Object referenced multiple times in trailer should be compressible"
+ );
+}
+
+#[test]
+fn test_encrypt_key_with_non_reference_value() {
+ let mut doc = Document::with_version("1.5");
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog"
+ });
+
+ // Set Encrypt to non-reference value (invalid but should not crash)
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Encrypt", Object::Null);
+
+ // Catalog should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should be compressible when Encrypt is not a reference"
+ );
+}
+
+#[test]
+fn test_missing_encrypt_key() {
+ let mut doc = Document::with_version("1.5");
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog"
+ });
+
+ let some_dict_id = doc.add_object(dictionary! {
+ "Filter" => "Standard" // Looks like encryption dict but not referenced as one
+ });
+
+ doc.trailer.set("Root", catalog_id);
+ // No Encrypt key in trailer
+
+ // Both should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should be compressible without Encrypt in trailer"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(some_dict_id, doc.objects.get(&some_dict_id).unwrap(), &doc),
+ "Dictionary that looks like encryption should be compressible if not referenced as Encrypt"
+ );
+}
+
+#[test]
+fn test_linearized_with_trailer_references() {
+ let mut doc = Document::with_version("1.5");
+
+ // Add linearization dictionary
+ let _lin_id = doc.add_object(dictionary! {
+ "Linearized" => 1
+ });
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog"
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Linearized PDF"
+ });
+
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+
+ // In linearized PDF, catalog cannot be compressed but info can
+ assert!(
+ !ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Catalog should NOT be compressible in linearized PDF"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(info_id, doc.objects.get(&info_id).unwrap(), &doc),
+ "Info should be compressible even in linearized PDF"
+ );
+}
+
+#[test]
+fn test_indirect_object_chain() {
+ let mut doc = Document::with_version("1.5");
+
+ // Create a chain of objects
+ let obj3_id = doc.add_object(dictionary! {
+ "Level" => 3
+ });
+
+ let obj2_id = doc.add_object(dictionary! {
+ "Level" => 2,
+ "Next" => obj3_id
+ });
+
+ let obj1_id = doc.add_object(dictionary! {
+ "Level" => 1,
+ "Next" => obj2_id
+ });
+
+ // Only reference the first in trailer
+ doc.trailer.set("Chain", obj1_id);
+
+ // All should be compressible (trailer only directly references obj1)
+ assert!(
+ ObjectStream::can_be_compressed(obj1_id, doc.objects.get(&obj1_id).unwrap(), &doc),
+ "Object directly referenced in trailer should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(obj2_id, doc.objects.get(&obj2_id).unwrap(), &doc),
+ "Object indirectly referenced should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(obj3_id, doc.objects.get(&obj3_id).unwrap(), &doc),
+ "Object indirectly referenced should be compressible"
+ );
+}
+
+#[test]
+fn test_real_world_trailer_structure() {
+ let mut doc = Document::with_version("1.5");
+
+ // Simulate a real PDF trailer structure
+ let pages_id = doc.new_object_id();
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ "Version" => "/1.5"
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Real World PDF",
+ "Author" => "Test Suite",
+ "Subject" => "Testing trailer compression",
+ "Creator" => "lopdf",
+ "Producer" => "lopdf test",
+ "CreationDate" => "D:20250101120000Z",
+ "ModDate" => "D:20250807120000Z"
+ });
+
+ // Typical trailer entries
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+ doc.trailer.set("Size", Object::Integer(50));
+ doc.trailer.set(
+ "ID",
+ Object::Array(vec![
+ Object::String(b"<4E4F204944454153>".to_vec(), lopdf::StringFormat::Hexadecimal),
+ Object::String(b"<4E4F204944454153>".to_vec(), lopdf::StringFormat::Hexadecimal),
+ ]),
+ );
+
+ // Both catalog and info should be compressible
+ assert!(
+ ObjectStream::can_be_compressed(catalog_id, doc.objects.get(&catalog_id).unwrap(), &doc),
+ "Real-world catalog should be compressible"
+ );
+ assert!(
+ ObjectStream::can_be_compressed(info_id, doc.objects.get(&info_id).unwrap(), &doc),
+ "Real-world info dictionary should be compressible"
+ );
+}
+
+#[test]
+fn test_compression_with_save_integration() {
+ use lopdf::SaveOptions;
+
+ let mut doc = Document::with_version("1.5");
+ let pages_id = doc.new_object_id();
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()]
+ });
+
+ doc.objects.insert(
+ pages_id,
+ Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1
+ }),
+ );
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id
+ });
+
+ let info_id = doc.add_object(dictionary! {
+ "Title" => "Compression Test",
+ "Keywords" => "test, compression, object streams"
+ });
+
+ doc.trailer.set("Root", catalog_id);
+ doc.trailer.set("Info", info_id);
+
+ // Save with object streams
+ let options = SaveOptions::builder().use_object_streams(true).build();
+
+ let mut output = Vec::new();
+ doc.save_with_options(&mut output, options).unwrap();
+
+ let content = String::from_utf8_lossy(&output);
+
+ // Verify object streams exist
+ assert!(content.contains("/ObjStm"), "Object streams should be created");
+
+ // Verify trailer-referenced objects are compressed
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Type/Catalog", catalog_id.0)),
+ "Catalog should be in object stream"
+ );
+ assert!(
+ !content.contains(&format!("{} 0 obj\n<</Title", info_id.0)),
+ "Info should be in object stream"
+ );
+
+ // Load and verify the PDF is valid
+ let loaded = Document::load_mem(&output).unwrap();
+ assert!(loaded.trailer.get(b"Root").is_ok(), "Loaded PDF should have valid Root");
+ assert!(loaded.trailer.get(b"Info").is_ok(), "Loaded PDF should have valid Info");
+}
diff --git a/vendor/lopdf/tests/unicode.rs b/vendor/lopdf/tests/unicode.rs
new file mode 100644
index 000000000..3872aad11
--- /dev/null
+++ b/vendor/lopdf/tests/unicode.rs
@@ -0,0 +1,147 @@
+use lopdf::content::{Content, Operation};
+use lopdf::{Document, Object, Stream, StringFormat, dictionary};
+
+#[test]
+fn unicode_can_be_written_to_pdf_and_read() {
+ let mut doc = Document::new();
+
+ // literal corresponds to the chars:
+ // U+1F600
+ // U+1F527
+ // U+1F528
+ // which are encoded in font cmap with the following hex
+ // <005F>
+ // <0060>
+ // <0061>
+ // please mind that indicated BaseFont might not contain
+ // those unicode emojis in practice
+ let unicode_literal = "😀🔧🔨";
+ let literal_encoded_with_cmap = [0x00, 0x5F, 0x00, 0x60, 0x00, 0x61];
+
+ // majority of below code correspond to create document example
+ // we are just inserting an appropriate unicode text
+ // and Type0 font with approriate characters encoding
+ let pages_id = doc.new_object_id();
+
+ let cmap_stream_id = doc.add_object(Stream::new(
+ dictionary! {
+ "Length" => 437
+ },
+ b"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo
+<< /Registry (Adobe)
+/Ordering (UCS)
+/Supplement 0
+>> def
+/CMapName /Adobe-Identity-UCS def
+/CMapType 2 def
+1 begincodespacerange
+<0000> <FFFF>
+endcodespacerange
+2 beginbfrange
+<0000> <005E> <0020>
+<005F> <0061> [<D83DDE00> <D83DDD27> <D83DDD28>]
+endbfrange
+1 beginbfchar
+<3A51> <D840DC3E>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end"
+ .to_vec(),
+ ));
+
+ let font_id = doc.add_object(dictionary! {
+ "Type" => "Font",
+ "Subtype" => "Type0",
+ "BaseFont" => "Ryumin-Light",
+ "Encoding" => "Identity-H",
+ "ToUnicode" => Object::Reference(cmap_stream_id)
+ });
+
+ let resources_id = doc.add_object(dictionary! {
+ "Font" => dictionary! {
+ "F1" => font_id,
+ },
+ });
+
+ // Create content with the prepared emoji string encoded according to values in our font cmap
+ let content = Content {
+ operations: vec![
+ Operation::new("BT", vec![]),
+ Operation::new("Tf", vec!["F1".into(), 48.into()]),
+ Operation::new("Td", vec![100.into(), 600.into()]),
+ Operation::new(
+ "Tj",
+ vec![Object::String(
+ literal_encoded_with_cmap.to_vec(),
+ StringFormat::Hexadecimal,
+ )],
+ ),
+ Operation::new("ET", vec![]),
+ ],
+ };
+
+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
+
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => pages_id,
+ "Contents" => content_id,
+ });
+
+ let pages = dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![page_id.into()],
+ "Count" => 1,
+ "Resources" => resources_id,
+ "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
+ };
+
+ // using insert() here, instead of add_object() since the id is already known.
+ doc.objects.insert(pages_id, Object::Dictionary(pages));
+
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => pages_id,
+ });
+
+ doc.trailer.set("Root", catalog_id);
+ doc.compress();
+
+ let extracted_text = get_text_from_first_page(&doc);
+
+ assert_eq!(extracted_text.trim_end(), unicode_literal);
+}
+
+fn get_text_from_first_page(doc: &Document) -> String {
+ let mut pages = doc.get_pages();
+ let first_page = pages.first_entry().expect("Expected pages to be non empty");
+
+ doc.extract_text(&[*first_page.key()])
+ .expect("Expected to find text on the first page")
+}
+
+#[cfg(not(feature = "async"))]
+#[test]
+fn unicode_can_be_extracted_from_loaded_pdf() -> lopdf::Result<()> {
+ let doc = Document::load("assets/unicode.pdf")?;
+ let extracted_text = get_text_from_first_page(&doc);
+ // extract text can currently map a consecutive fragment of text
+ // to one divided into multiple lines, therefore we have to remove the
+ // new lines
+ assert_eq!(extracted_text.replace("\n", ""), "😀🔧🔨");
+ Ok(())
+}
+
+#[cfg(feature = "async")]
+#[tokio::test]
+async fn unicode_can_be_extracted_from_loaded_pdf() -> lopdf::Result<()> {
+ let doc = Document::load("assets/unicode.pdf").await?;
+ let extracted_text = get_text_from_first_page(&doc);
+ assert_eq!(extracted_text.replace("\n", ""), "😀🔧🔨");
+ Ok(())
+}
diff --git a/vendor/lopdf/tests/utils.rs b/vendor/lopdf/tests/utils.rs
new file mode 100644
index 000000000..99d5a9b20
--- /dev/null
+++ b/vendor/lopdf/tests/utils.rs
@@ -0,0 +1,37 @@
+use lopdf::{Document, IncrementalDocument, Result};
+use std::fmt::Display;
+use std::path::Path;
+
+#[allow(dead_code)]
+pub fn load_document<P>(path: P) -> Result<Document>
+where
+ P: AsRef<Path> + Display,
+{
+ #[cfg(feature = "async")]
+ let doc = tokio::runtime::Runtime::new()?.block_on(async move {
+ Document::load(&path)
+ .await
+ .unwrap_or_else(|_| panic!("Failed to load {}", path))
+ });
+ #[cfg(not(feature = "async"))]
+ let doc = Document::load(path)?;
+
+ Ok(doc)
+}
+
+#[allow(dead_code)]
+pub fn load_incremental_document<P>(path: P) -> Result<IncrementalDocument>
+where
+ P: AsRef<Path> + Display,
+{
+ #[cfg(feature = "async")]
+ let doc = tokio::runtime::Runtime::new()?.block_on(async move {
+ IncrementalDocument::load(&path)
+ .await
+ .unwrap_or_else(|_| panic!("Failed to load {}", path))
+ });
+ #[cfg(not(feature = "async"))]
+ let doc = IncrementalDocument::load(path)?;
+
+ Ok(doc)
+}
diff --git a/vendor/lopdf/tests/xref_reconstruction.rs b/vendor/lopdf/tests/xref_reconstruction.rs
new file mode 100644
index 000000000..f5f68c8b3
--- /dev/null
+++ b/vendor/lopdf/tests/xref_reconstruction.rs
@@ -0,0 +1,382 @@
+use lopdf::{Document, LoadOptions, Object};
+
+/// Append objects, returning each one's `(number, physical offset)`.
+fn append_objects(pdf: &mut Vec<u8>, bodies: &[(u32, u16, String)]) -> Vec<(u32, usize)> {
+ let mut offsets = Vec::new();
+ for (number, generation, body) in bodies {
+ offsets.push((*number, pdf.len()));
+ pdf.extend_from_slice(format!("{number} {generation} obj\n{body}\nendobj\n").as_bytes());
+ }
+ offsets
+}
+
+/// Append a cross-reference table and trailer whose `startxref` records
+/// `startxref_value` (tests pass broken values to force the fallback).
+fn append_xref_trailer(pdf: &mut Vec<u8>, offsets: &[(u32, usize)], trailer: &str, startxref_value: usize) {
+ pdf.extend_from_slice(b"xref\n");
+ pdf.extend_from_slice(format!("0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
+ for (_, offset) in offsets {
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(format!("trailer\n{trailer}\nstartxref\n{startxref_value}\n%%EOF\n").as_bytes());
+}
+
+/// One-page document whose content stream embeds object-like decoy tokens
+/// (`99 88 objx`, `1 2 objects`) that must never become markers.
+fn sample_bodies() -> Vec<(u32, u16, String)> {
+ let contents = b"BT /F1 12 Tf 20 100 Td (Hello World) Tj (99 88 objx) Tj (1 2 objects) Tj ET";
+ vec![
+ (1, 0, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
+ (2, 0, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string()),
+ (
+ 3,
+ 0,
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
+ ),
+ (
+ 4,
+ 0,
+ format!(
+ "<< /Length {} >>\nstream\n{}\nendstream",
+ contents.len(),
+ std::str::from_utf8(contents).unwrap()
+ ),
+ ),
+ ]
+}
+
+fn new_pdf() -> Vec<u8> {
+ b"%PDF-1.4\n".to_vec()
+}
+
+#[test]
+fn startxref_past_eof_is_reconstructed_from_object_markers() {
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.trailer.get(b"Root").is_ok());
+
+ assert!(document.get_object((99, 0)).is_err());
+
+ let metadata = Document::load_metadata_mem(&pdf).unwrap();
+ assert_eq!(metadata.page_count, 1);
+}
+
+#[test]
+fn strict_mode_does_not_reconstruct() {
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+ let strict = LoadOptions {
+ strict: true,
+ ..Default::default()
+ };
+
+ assert!(Document::load_mem_with_options(&pdf, strict).is_err());
+}
+
+#[test]
+fn startxref_pointing_into_a_stream_falls_back_to_reconstruction() {
+ // Pointer lands mid-payload, beyond the correction window.
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ let payload = pdf.windows(7).position(|window| window == b"stream\n").unwrap() + 7;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", payload + 30);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ let Object::Stream(stream) = document.get_object((4, 0)).unwrap() else {
+ panic!("reconstructed object must remain a stream");
+ };
+ assert!(stream.content.starts_with(b"BT"));
+}
+
+#[test]
+fn reconstruction_prefers_newer_revisions_of_duplicated_objects() {
+ // A second revision redefines object 2; its startxref is corrupted.
+ let mut pdf = new_pdf();
+ let mut offsets = append_objects(&mut pdf, &sample_bodies());
+ let first_startxref = pdf.len();
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", first_startxref);
+
+ let revised_pages = "<< /Type /Pages /Kids [3 0 R] /Count 42 >>";
+ let revision_offset = pdf.len();
+ pdf.extend_from_slice(format!("2 0 obj\n{revised_pages}\nendobj\n").as_bytes());
+ offsets.retain(|(number, _)| *number != 2);
+ offsets.push((2, revision_offset));
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ let count = document
+ .get_object((2, 0))
+ .unwrap()
+ .as_dict()
+ .unwrap()
+ .get(b"Count")
+ .unwrap()
+ .as_i64()
+ .unwrap();
+ assert_eq!(count, 42);
+ assert_eq!(document.get_pages().len(), 1);
+}
+
+#[test]
+fn reconstruction_skips_trailers_whose_root_was_not_found() {
+ // A trailing bogus trailer references absent catalog object 77.
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+ pdf.extend_from_slice(b"trailer\n<< /Size 12 /Root 77 0 R >>\n%%EOF\n");
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((77, 0)).is_err());
+}
+
+#[test]
+fn reconstruction_fails_when_no_trailer_has_a_usable_root() {
+ let mut pdf = new_pdf();
+ append_objects(&mut pdf, &sample_bodies());
+ pdf.extend_from_slice(b"trailer\n<< /Size 5 >>\n");
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &[], "", broken_startxref);
+
+ assert!(Document::load_mem(&pdf).is_err());
+}
+
+/// A one-page document whose uncompressed content stream embeds whole
+/// object-header lines that must never be scanned as markers.
+fn sample_bodies_with_decoy_stream() -> Vec<(u32, u16, String)> {
+ let contents = b"(1 0 obj)\nBT ET\n5 0 obj";
+ let mut bodies = sample_bodies();
+ bodies[3] = (
+ 4,
+ 0,
+ format!(
+ "<< /Length {} >>\nstream\n{}\nendstream",
+ contents.len(),
+ std::str::from_utf8(contents).unwrap()
+ ),
+ );
+ bodies
+}
+
+#[test]
+fn reconstruction_ignores_object_headers_inside_streams() {
+ // The decoys sit at line starts inside the payload; the `(1 0 obj)` one
+ // must not overwrite the genuine catalog entry for object 1.
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies_with_decoy_stream());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 6 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((1, 0)).unwrap().as_dict().unwrap().has(b"Type"));
+ assert!(document.get_object((5, 0)).is_err());
+}
+
+#[test]
+fn reconstruction_rejects_absurd_object_numbers() {
+ // A comment forging a huge object header would inflate size/max_id via
+ // Xref::insert and eventually overflow new_object_id().
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ pdf.extend_from_slice(b"%4294967290 0 obj\n");
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+
+ let mut document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.max_id, 4);
+ assert_eq!(document.new_object_id(), (5, 0));
+}
+
+#[test]
+fn reconstructed_size_counts_object_numbers_not_physical_copies() {
+ // Two revisions of every object: 8 markers, but the highest number is 4.
+ let mut pdf = new_pdf();
+ let mut offsets = append_objects(&mut pdf, &sample_bodies());
+ offsets.extend(append_objects(&mut pdf, &sample_bodies()));
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 9 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.max_id, 4);
+ assert_eq!(document.reference_table.size, 5);
+ assert_eq!(document.get_pages().len(), 1);
+}
+
+/// Append an `/ObjStm` container holding `members` (object number + body).
+fn append_objstm(pdf: &mut Vec<u8>, number: u32, members: &[(u32, &[u8])]) {
+ use std::io::Write as _;
+
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+
+ let mut index = String::new();
+ let mut body: Vec<u8> = Vec::new();
+ for (id, data) in members {
+ index.push_str(&format!("{id} {}\n", body.len()));
+ body.extend_from_slice(data);
+ }
+ let first = index.len();
+ let content = [index.as_bytes(), body.as_slice()].concat();
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(&content).unwrap();
+ let compressed = encoder.finish().unwrap();
+
+ pdf.extend_from_slice(
+ format!(
+ "{number} 0 obj\n<< /Type /ObjStm /N {} /First {first} /Length {} /Filter /FlateDecode >>\nstream\n",
+ members.len(),
+ compressed.len()
+ )
+ .as_bytes(),
+ );
+ pdf.extend_from_slice(&compressed);
+ pdf.extend_from_slice(b"\nendstream\nendobj\n");
+}
+
+#[test]
+fn reconstructed_max_id_covers_object_stream_members() {
+ // Objects 5-7 live inside the ObjStm container 2; only objects 1 and 2
+ // are scanned as markers, so max_id must still reach 7 after loading.
+ let mut pdf = new_pdf();
+ let pages = b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>";
+ let page = b"<< /Type /Page /Parent 5 0 R /MediaBox [0 0 200 200] >>";
+ let info = b"<< /Type /Info /Producer (x) >>";
+ let mut offsets = append_objects(&mut pdf, &[(1, 0, "<< /Type /Catalog /Pages 5 0 R >>".to_string())]);
+ let objstm_offset = pdf.len();
+ append_objstm(&mut pdf, 2, &[(5, pages), (6, page), (7, info)]);
+ offsets.push((2, objstm_offset));
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 8 /Root 1 0 R >>", broken_startxref);
+
+ let mut document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((7, 0)).is_ok());
+ assert_eq!(document.max_id, 7);
+ assert_eq!(document.new_object_id(), (8, 0));
+}
+
+/// Catalog, pages, and page bodies without the content stream object.
+fn page_tree_bodies() -> Vec<(u32, u16, String)> {
+ vec![
+ (1, 0, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
+ (2, 0, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string()),
+ (
+ 3,
+ 0,
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
+ ),
+ ]
+}
+
+#[test]
+fn reconstruction_recovers_objects_after_a_stream_without_endstream() {
+ // The damaged stream cannot bound its payload; objects written after it
+ // must still be scanned instead of dropping the whole fallback.
+ let mut pdf = new_pdf();
+ pdf.extend_from_slice(b"4 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstrXXm\nendobj\n");
+ let offsets = append_objects(&mut pdf, &page_tree_bodies());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((1, 0)).is_ok());
+}
+
+#[test]
+fn reconstruction_bounds_unterminated_stream_by_its_length_hint() {
+ // Without `endstream` the payload is unbounded; honouring the direct
+ // /Length keeps its line-start decoy from shadowing the catalog.
+ let mut pdf = new_pdf();
+ let mut offsets = append_objects(&mut pdf, &page_tree_bodies());
+ let payload = b"1 0 obj\n<< /Bogus true >>\nendobj\n";
+ let fourth_offset = pdf.len();
+ pdf.extend_from_slice(format!("4 0 obj\n<< /Length {} >>\nstream\n", payload.len()).as_bytes());
+ pdf.extend_from_slice(payload);
+ pdf.extend_from_slice(b"endstrXXm\nendobj\n");
+ offsets.push((4, fourth_offset));
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((1, 0)).unwrap().as_dict().unwrap().has(b"Type"));
+}
+
+#[test]
+fn reconstruction_does_not_use_a_previous_objects_length_hint() {
+ // Object 4's damaged stream carries no /Length; the stale `/Length 300`
+ // from object 5's dictionary must not skip past objects 1-3.
+ let mut pdf = new_pdf();
+ let fifth_offset = pdf.len();
+ pdf.extend_from_slice(b"5 0 obj\n<< /Length 300 >>\nstream\nBT ET\nendstream\nendobj\n");
+ let fourth_offset = pdf.len();
+ pdf.extend_from_slice(b"4 0 obj\n<< /Type /XObject >>\nstream\nPAYLOAD\nendstrXXm\nendobj\n");
+ let mut offsets = append_objects(&mut pdf, &page_tree_bodies());
+ offsets.push((4, fourth_offset));
+ offsets.push((5, fifth_offset));
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 6 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert!(document.get_object((1, 0)).unwrap().as_dict().unwrap().has(b"Type"));
+}
+
+#[test]
+fn reconstruction_accepts_indented_object_headers() {
+ // Real generators indent object headers; blanks between the line start
+ // and the digits must not hide the marker.
+ let mut pdf = new_pdf();
+ let first_offset = pdf.len();
+ pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ let second_offset = pdf.len();
+ pdf.extend_from_slice(b" 2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
+ let third_offset = pdf.len();
+ pdf.extend_from_slice(b"\t3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>\nendobj\n");
+ let offsets = vec![(1, first_offset), (2, second_offset), (3, third_offset)];
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 4 /Root 1 0 R >>", broken_startxref);
+
+ let document = Document::load_mem(&pdf).unwrap();
+ assert_eq!(document.get_pages().len(), 1);
+ assert_eq!(document.max_id, 3);
+}
+
+#[test]
+fn incremental_update_omits_prev_without_a_real_xref_location() {
+ // Reconstructed document: no on-disk xref exists, so no /Prev may point
+ // at end-of-file.
+ let mut pdf = new_pdf();
+ let offsets = append_objects(&mut pdf, &sample_bodies());
+ let broken_startxref = pdf.len() + 4096;
+ append_xref_trailer(&mut pdf, &offsets, "<< /Size 5 /Root 1 0 R >>", broken_startxref);
+ let document = Document::load_mem(&pdf).unwrap();
+
+ let update = Document::new_from_prev(&document);
+ assert!(update.trailer.get(b"Prev").is_err());
+
+ // Contrast: a normally loaded document keeps its /Prev chain intact.
+ let mut valid = new_pdf();
+ let valid_offsets = append_objects(&mut valid, &sample_bodies());
+ let xref_pos = valid.len();
+ append_xref_trailer(&mut valid, &valid_offsets, "<< /Size 5 /Root 1 0 R >>", xref_pos);
+ let valid_document = Document::load_mem(&valid).unwrap();
+
+ let valid_update = Document::new_from_prev(&valid_document);
+ assert_eq!(
+ valid_update.trailer.get(b"Prev").unwrap().as_i64().unwrap(),
+ xref_pos as i64
+ );
+}
diff --git a/vendor/lopdf/tests/xref_stream_bounds.rs b/vendor/lopdf/tests/xref_stream_bounds.rs
new file mode 100644
index 000000000..016ddff36
--- /dev/null
+++ b/vendor/lopdf/tests/xref_stream_bounds.rs
@@ -0,0 +1,231 @@
+//! A cross-reference stream declares how many entries it holds in its `/Index`
+//! array, but the entries themselves live in the (decoded) stream body. If the
+//! declared count is allowed to run past what the body can hold, `load` spins on
+//! an attacker-controlled number instead of the bytes actually present.
+
+#![cfg(not(feature = "async"))]
+
+use std::io::Write;
+
+use flate2::{Compression, write::ZlibEncoder};
+use lopdf::{Document, Error, LoadOptions, ParseError, SaveOptions, Stream, dictionary};
+
+/// A PDF whose only cross-reference is an xref stream with the given `/W` widths,
+/// `/Index [0 count]`, and `body` as an uncompressed stream body.
+fn xref_stream_pdf(w: [i64; 3], count: i64, body: &[u8]) -> Vec<u8> {
+ xref_stream_pdf_with_index(w, &format!("0 {count}"), body)
+}
+
+fn xref_stream_pdf_with_index(w: [i64; 3], index: &str, body: &[u8]) -> Vec<u8> {
+ let mut pdf = Vec::new();
+ pdf.extend_from_slice(b"%PDF-1.5\n");
+ let obj_offset = pdf.len();
+ pdf.extend_from_slice(b"1 0 obj\n");
+ pdf.extend_from_slice(
+ format!(
+ "<< /Type /XRef /Size 4 /W [{} {} {}] /Index [{index}] /Root 1 0 R /Length {} >>\n",
+ w[0],
+ w[1],
+ w[2],
+ body.len()
+ )
+ .as_bytes(),
+ );
+ pdf.extend_from_slice(b"stream\n");
+ pdf.extend_from_slice(body);
+ pdf.extend_from_slice(b"\nendstream\nendobj\n");
+ pdf.extend_from_slice(format!("startxref\n{obj_offset}\n%%EOF").as_bytes());
+ pdf
+}
+
+fn compressed_xref_stream_pdf(entries: usize) -> Vec<u8> {
+ let mut pdf = b"%PDF-1.5\n".to_vec();
+ let catalog_offset = pdf.len();
+ pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
+ let xref_offset = pdf.len();
+
+ let mut body = Vec::with_capacity(entries * 5);
+ for id in 0..entries {
+ let (entry_type, offset): (u8, u32) = match id {
+ 1 => (1, catalog_offset as u32),
+ 2 => (1, xref_offset as u32),
+ _ => (0, 0),
+ };
+ body.push(entry_type);
+ body.extend_from_slice(&offset.to_be_bytes()[1..4]);
+ body.push(0);
+ }
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(&body).unwrap();
+ let compressed_body = encoder.finish().unwrap();
+
+ pdf.extend_from_slice(b"2 0 obj\n");
+ pdf.extend_from_slice(
+ format!(
+ "<< /Type /XRef /Size {entries} /W [1 3 1] /Index [0 {entries}] /Root 1 0 R \
+ /Filter /FlateDecode /Length {} >>\n",
+ compressed_body.len()
+ )
+ .as_bytes(),
+ );
+ pdf.extend_from_slice(b"stream\n");
+ pdf.extend_from_slice(&compressed_body);
+ pdf.extend_from_slice(b"\nendstream\nendobj\n");
+ pdf.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF").as_bytes());
+ pdf
+}
+
+fn incremental_classic_xref_pdf(objects: usize) -> Vec<u8> {
+ let mut pdf = b"%PDF-1.4\n".to_vec();
+ let mut offsets = Vec::with_capacity(objects);
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
+ for id in 2..=objects {
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(format!("{id} 0 obj\n{id}\nendobj\n").as_bytes());
+ }
+
+ let first_xref = pdf.len();
+ pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects + 1).as_bytes());
+ for offset in offsets {
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\n", objects + 1).as_bytes());
+ pdf.extend_from_slice(format!("startxref\n{first_xref}\n%%EOF\n").as_bytes());
+
+ let new_offset = pdf.len();
+ let new_id = objects + 1;
+ pdf.extend_from_slice(format!("{new_id} 0 obj\n99\nendobj\n").as_bytes());
+ let second_xref = pdf.len();
+ pdf.extend_from_slice(format!("xref\n{new_id} 1\n{new_offset:010} 00000 n \n").as_bytes());
+ pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R /Prev {first_xref} >>\n", new_id + 1).as_bytes());
+ pdf.extend_from_slice(format!("startxref\n{second_xref}\n%%EOF").as_bytes());
+ pdf
+}
+
+// With `/W [0 0 0]` every entry reads zero bytes, so before the bound the loop ran
+// purely on `/Index`. A 137-byte file claiming a million entries returned Ok with a
+// million-node xref table; `i64::MAX` never returned at all. It must be rejected,
+// and quickly.
+#[test]
+fn zero_width_xref_stream_is_rejected() {
+ let pdf = xref_stream_pdf([0, 0, 0], 1_000_000, b"");
+ match Document::load_mem(&pdf) {
+ Err(Error::Parse(ParseError::InvalidXref)) => {}
+ Err(other) => panic!("expected InvalidXref, got {other:?}"),
+ Ok(doc) => panic!(
+ "a 137-byte file claiming 1,000,000 xref entries loaded with {} entries",
+ doc.reference_table.entries.len()
+ ),
+ }
+}
+
+// Non-zero widths already terminate once the reader runs dry, but only after
+// inserting one map entry per byte first. Bounding the count against the bytes
+// present stops that up front: three body bytes at `/W [1 1 1]` hold one entry, so
+// a section claiming a million is malformed.
+#[test]
+fn index_count_past_stream_length_is_rejected() {
+ let pdf = xref_stream_pdf([1, 1, 1], 1_000_000, &[1, 0, 0]);
+ match Document::load_mem(&pdf) {
+ Err(Error::Parse(ParseError::InvalidXref)) => {}
+ Err(other) => panic!("expected InvalidXref, got {other:?}"),
+ Ok(_) => panic!("an /Index count far past the stream length was accepted"),
+ }
+}
+
+#[test]
+fn negative_index_count_is_rejected() {
+ let pdf = xref_stream_pdf([1, 1, 1], -1, &[]);
+ assert!(matches!(
+ Document::load_mem(&pdf),
+ Err(Error::Parse(ParseError::InvalidXref))
+ ));
+}
+
+#[test]
+fn three_byte_xref_records_are_accepted() {
+ let pdf = xref_stream_pdf([1, 2, 0], 2, &[0, 0, 0, 1, 0, 9]);
+ Document::load_mem(&pdf).expect("/W [1 2 0] records should remain accepted");
+}
+
+#[test]
+fn single_index_section_matching_stream_length_is_accepted() {
+ let body = [1, 0, 0, 0, 9, 0, 0];
+ let pdf = xref_stream_pdf_with_index([1, 4, 2], "0 1", &body);
+ Document::load_mem(&pdf).expect("one seven-byte record should fit a seven-byte body");
+}
+
+#[test]
+fn total_index_count_past_stream_length_is_rejected() {
+ let body = [1, 0, 0, 0, 9, 0, 0];
+ let pdf = xref_stream_pdf_with_index([1, 4, 2], "0 1 2 1", &body);
+ assert!(matches!(
+ Document::load_mem(&pdf),
+ Err(Error::Parse(ParseError::InvalidXref))
+ ));
+}
+
+// `/W [0 1 0]` records consume one decoded byte but retain a full map entry.
+// Floor the effective width so a valid-sized body cannot amplify into a much
+// larger in-memory xref table, independently of any decompression budget.
+#[test]
+fn degenerate_narrow_xref_records_are_rejected() {
+ let pdf = xref_stream_pdf([0, 1, 0], 4, &[0; 4]);
+ let result = Document::load_mem(&pdf);
+ assert!(matches!(result, Err(Error::Parse(ParseError::InvalidXref))));
+}
+
+#[test]
+fn realistic_compressed_xref_stream_loads_under_budget() {
+ let pdf = compressed_xref_stream_pdf(300);
+ Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(2_000))
+ .expect("a 1,500-byte xref stream should load under a 2,000-byte budget");
+}
+
+#[test]
+fn incremental_classic_xref_loads_under_budget() {
+ let pdf = incremental_classic_xref_pdf(400);
+ Document::load_mem_with_options(&pdf, LoadOptions::with_max_decompressed_size(2_000))
+ .expect("classic xref entries should not consume the decompression budget");
+}
+
+// The bound is derived from the real per-entry width, so a genuine xref stream
+// whose `/Index` matches its body still loads. Written by lopdf's own writer to be
+// sure the shape is exactly what the reader expects.
+#[test]
+fn valid_xref_stream_still_loads() {
+ let mut doc = Document::with_version("1.5");
+ let content_id = doc.add_object(Stream::new(dictionary! {}, b"BT ET".to_vec()));
+ let pages_id = doc.new_object_id();
+ let page_id = doc.add_object(dictionary! {
+ "Type" => "Page",
+ "Parent" => lopdf::Object::Reference(pages_id),
+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
+ "Contents" => lopdf::Object::Reference(content_id),
+ });
+ doc.objects.insert(
+ pages_id,
+ lopdf::Object::Dictionary(dictionary! {
+ "Type" => "Pages",
+ "Kids" => vec![lopdf::Object::Reference(page_id)],
+ "Count" => 1,
+ }),
+ );
+ let catalog_id = doc.add_object(dictionary! {
+ "Type" => "Catalog",
+ "Pages" => lopdf::Object::Reference(pages_id),
+ });
+ doc.trailer.set("Root", lopdf::Object::Reference(catalog_id));
+
+ let options = SaveOptions::builder()
+ .use_object_streams(false)
+ .use_xref_streams(true)
+ .build();
+ let mut buffer = Vec::new();
+ doc.save_with_options(&mut buffer, options).unwrap();
+
+ let reloaded = Document::load_mem(&buffer).unwrap();
+ assert!(reloaded.get_object(catalog_id).is_ok());
+ assert_eq!(reloaded.get_pages().len(), 1);
+}