Debian Codegraph @

debian/missing-sources/lopdf/README.md

raw symbols SCIP
1 # lopdf
2
3 [![Crates.io](https://img.shields.io/crates/v/lopdf.svg)](https://crates.io/crates/lopdf)
4 [![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)
5 [![Docs]( https://docs.rs/lopdf/badge.svg)](https://docs.rs/lopdf)
6
7 A Rust library for PDF document manipulation.
8
9 A useful reference for understanding the PDF file format and the
10 eventual usage of this library is the
11 [PDF 1.7 Reference Document](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf).
12 The PDF 2.0 specification is available [here](https://www.pdfa.org/announcing-no-cost-access-to-iso-32000-2-pdf-2-0/).
13
14 ## Requirements
15
16 - **Rust 1.85 or later** - Required for Rust 2024 edition features and object streams support
17 - To check your Rust version: `rustc --version`
18 - To update Rust: `rustup update`
19
20 ## Example Code
21
22 * Create PDF document
23
24 ```rust
25 use lopdf::dictionary;
26 use lopdf::{Document, Object, Stream};
27 use lopdf::content::{Content, Operation};
28
29 // `with_version` specifes the PDF version this document complies with.
30 let mut doc = Document::with_version("1.5");
31 // Object IDs are used for cross referencing in PDF documents.
32 // `lopdf` helps keep track of them for us. They are simple integers.
33 // Calls to `doc.new_object_id` and `doc.add_object` return an object ID.
34
35 // "Pages" is the root node of the page tree.
36 let pages_id = doc.new_object_id();
37
38 // Fonts are dictionaries. The "Type", "Subtype" and "BaseFont" tags
39 // are straight out of the PDF spec.
40 //
41 // The dictionary macro is a helper that allows complex
42 // key-value relationships to be represented in a simpler
43 // visual manner, similar to a match statement.
44 // A dictionary is implemented as an IndexMap of Vec<u8>, and Object
45 let font_id = doc.add_object(dictionary! {
46 // type of dictionary
47 "Type" => "Font",
48 // type of font, type1 is simple postscript font
49 "Subtype" => "Type1",
50 // basefont is postscript name of font for type1 font.
51 // See PDF reference document for more details
52 "BaseFont" => "Courier",
53 });
54
55 // Font dictionaries need to be added into resource
56 // dictionaries in order to be used.
57 // Resource dictionaries can contain more than just fonts,
58 // but normally just contains fonts.
59 // Only one resource dictionary is allowed per page tree root.
60 let resources_id = doc.add_object(dictionary! {
61 // Fonts are actually triplely nested dictionaries. Fun!
62 "Font" => dictionary! {
63 // F1 is the font name used when writing text.
64 // It must be unique in the document. It does not
65 // have to be F1
66 "F1" => font_id,
67 },
68 });
69
70 // `Content` is a wrapper struct around an operations struct that contains
71 // a vector of operations. The operations struct contains a vector of
72 // that match up with a particular PDF operator and operands.
73 // Refer to the PDF spec for more details on the operators and operands
74 // Note, the operators and operands are specified in a reverse order
75 // from how they actually appear in the PDF file itself.
76 let content = Content {
77 operations: vec![
78 // BT begins a text element. It takes no operands.
79 Operation::new("BT", vec![]),
80 // Tf specifies the font and font size.
81 // Font scaling is complicated in PDFs.
82 // Refer to the spec for more info.
83 // The `into()` methods convert the types into
84 // an enum that represents the basic object types in PDF documents.
85 Operation::new("Tf", vec!["F1".into(), 48.into()]),
86 // Td adjusts the translation components of the text matrix.
87 // When used for the first time after BT, it sets the initial
88 // text position on the page.
89 // Note: PDF documents have Y=0 at the bottom. Thus 600 to print text near the top.
90 Operation::new("Td", vec![100.into(), 600.into()]),
91 // Tj prints a string literal to the page. By default, this is black text that is
92 // filled in. There are other operators that can produce various textual effects and
93 // colors
94 Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
95 // ET ends the text element.
96 Operation::new("ET", vec![]),
97 ],
98 };
99
100 // Streams are a dictionary followed by a (possibly encoded) sequence of bytes.
101 // What that sequence of bytes represents, depends on the context.
102 // The stream dictionary is set internally by lopdf and normally doesn't
103 // need to be manually manipulated. It contains keys such as
104 // Length, Filter, DecodeParams, etc.
105 let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
106
107 // Page is a dictionary that represents one page of a PDF file.
108 // Its required fields are "Type", "Parent" and "Contents".
109 let page_id = doc.add_object(dictionary! {
110 "Type" => "Page",
111 "Parent" => pages_id,
112 "Contents" => content_id,
113 });
114
115 // Again, "Pages" is the root of the page tree. The ID was already created
116 // at the top of the page, since we needed it to assign to the parent element
117 // of the page dictionary.
118 //
119 // These are just the basic requirements for a page tree root object.
120 // There are also many additional entries that can be added to the dictionary,
121 // if needed. Some of these can also be defined on the page dictionary itself,
122 // and not inherited from the page tree root.
123 let pages = dictionary! {
124 // Type of dictionary
125 "Type" => "Pages",
126 // Vector of page IDs in document. Normally would contain more than one ID
127 // and be produced using a loop of some kind.
128 "Kids" => vec![page_id.into()],
129 // Page count
130 "Count" => 1,
131 // ID of resources dictionary, defined earlier
132 "Resources" => resources_id,
133 // A rectangle that defines the boundaries of the physical or digital media.
134 // This is the "page size".
135 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
136 };
137
138 // Using `insert()` here, instead of `add_object()` since the ID is already known.
139 doc.objects.insert(pages_id, Object::Dictionary(pages));
140
141 // Creating document catalog.
142 // There are many more entries allowed in the catalog dictionary.
143 let catalog_id = doc.add_object(dictionary! {
144 "Type" => "Catalog",
145 "Pages" => pages_id,
146 });
147
148 // The "Root" key in trailer is set to the ID of the document catalog,
149 // the remainder of the trailer is set during `doc.save()`.
150 doc.trailer.set("Root", catalog_id);
151 doc.compress();
152
153 // Store file in current working directory.
154 // Note: Line is excluded when running tests
155 if false {
156 // Traditional save
157 doc.save("example.pdf").unwrap();
158
159 // Or save with object streams for smaller file size
160 let mut file = std::fs::File::create("example_compressed.pdf").unwrap();
161 doc.save_modern(&mut file).unwrap();
162 }
163 ```
164
165 * Merge PDF documents
166
167 ```rust
168 use lopdf::dictionary;
169
170 use std::collections::BTreeMap;
171
172 use lopdf::content::{Content, Operation};
173 use lopdf::{Document, Object, ObjectId, Stream, Bookmark};
174
175 pub fn generate_fake_document() -> Document {
176 let mut doc = Document::with_version("1.5");
177 let pages_id = doc.new_object_id();
178 let font_id = doc.add_object(dictionary! {
179 "Type" => "Font",
180 "Subtype" => "Type1",
181 "BaseFont" => "Courier",
182 });
183 let resources_id = doc.add_object(dictionary! {
184 "Font" => dictionary! {
185 "F1" => font_id,
186 },
187 });
188 let content = Content {
189 operations: vec![
190 Operation::new("BT", vec![]),
191 Operation::new("Tf", vec!["F1".into(), 48.into()]),
192 Operation::new("Td", vec![100.into(), 600.into()]),
193 Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
194 Operation::new("ET", vec![]),
195 ],
196 };
197 let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
198 let page_id = doc.add_object(dictionary! {
199 "Type" => "Page",
200 "Parent" => pages_id,
201 "Contents" => content_id,
202 "Resources" => resources_id,
203 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
204 });
205 let pages = dictionary! {
206 "Type" => "Pages",
207 "Kids" => vec![page_id.into()],
208 "Count" => 1,
209 };
210 doc.objects.insert(pages_id, Object::Dictionary(pages));
211 let catalog_id = doc.add_object(dictionary! {
212 "Type" => "Catalog",
213 "Pages" => pages_id,
214 });
215 doc.trailer.set("Root", catalog_id);
216
217 doc
218 }
219
220 fn main() -> std::io::Result<()> {
221 // Generate a stack of Documents to merge.
222 let documents = vec![
223 generate_fake_document(),
224 generate_fake_document(),
225 generate_fake_document(),
226 generate_fake_document(),
227 ];
228
229 // Define a starting `max_id` (will be used as start index for object_ids).
230 let mut max_id = 1;
231 let mut pagenum = 1;
232 // Collect all Documents Objects grouped by a map
233 let mut documents_pages = BTreeMap::new();
234 let mut documents_objects = BTreeMap::new();
235 let mut document = Document::with_version("1.5");
236
237 for mut doc in documents {
238 let mut first = false;
239 doc.renumber_objects_with(max_id);
240
241 max_id = doc.max_id + 1;
242
243 documents_pages.extend(
244 doc
245 .get_pages()
246 .into_iter()
247 .map(|(_, object_id)| {
248 if !first {
249 let bookmark = Bookmark::new(String::from(format!("Page_{}", pagenum)), [0.0, 0.0, 1.0], 0, object_id);
250 document.add_bookmark(bookmark, None);
251 first = true;
252 pagenum += 1;
253 }
254
255 (
256 object_id,
257 doc.get_object(object_id).unwrap().to_owned(),
258 )
259 })
260 .collect::<BTreeMap<ObjectId, Object>>(),
261 );
262 documents_objects.extend(doc.objects);
263 }
264
265 // "Catalog" and "Pages" are mandatory.
266 let mut catalog_object: Option<(ObjectId, Object)> = None;
267 let mut pages_object: Option<(ObjectId, Object)> = None;
268
269 // Process all objects except "Page" type
270 for (object_id, object) in documents_objects.iter() {
271 // We have to ignore "Page" (as are processed later), "Outlines" and "Outline" objects.
272 // All other objects should be collected and inserted into the main Document.
273 match object.type_name().unwrap_or(b"") {
274 b"Catalog" => {
275 // Collect a first "Catalog" object and use it for the future "Pages".
276 catalog_object = Some((
277 if let Some((id, _)) = catalog_object {
278 id
279 } else {
280 *object_id
281 },
282 object.clone(),
283 ));
284 }
285 b"Pages" => {
286 // Collect and update a first "Pages" object and use it for the future "Catalog"
287 // We have also to merge all dictionaries of the old and the new "Pages" object
288 if let Ok(dictionary) = object.as_dict() {
289 let mut dictionary = dictionary.clone();
290 if let Some((_, ref object)) = pages_object {
291 if let Ok(old_dictionary) = object.as_dict() {
292 dictionary.extend(old_dictionary);
293 }
294 }
295
296 pages_object = Some((
297 if let Some((id, _)) = pages_object {
298 id
299 } else {
300 *object_id
301 },
302 Object::Dictionary(dictionary),
303 ));
304 }
305 }
306 b"Page" => {} // Ignored, processed later and separately
307 b"Outlines" => {} // Ignored, not supported yet
308 b"Outline" => {} // Ignored, not supported yet
309 _ => {
310 document.objects.insert(*object_id, object.clone());
311 }
312 }
313 }
314
315 // If no "Pages" object found, abort.
316 if pages_object.is_none() {
317 println!("Pages root not found.");
318
319 return Ok(());
320 }
321
322 // Iterate over all "Page" objects and collect into the parent "Pages" created before
323 for (object_id, object) in documents_pages.iter() {
324 if let Ok(dictionary) = object.as_dict() {
325 let mut dictionary = dictionary.clone();
326 dictionary.set("Parent", pages_object.as_ref().unwrap().0);
327
328 document
329 .objects
330 .insert(*object_id, Object::Dictionary(dictionary));
331 }
332 }
333
334 // If no "Catalog" found, abort.
335 if catalog_object.is_none() {
336 println!("Catalog root not found.");
337
338 return Ok(());
339 }
340
341 let catalog_object = catalog_object.unwrap();
342 let pages_object = pages_object.unwrap();
343
344 // Build a new "Pages" with updated fields
345 if let Ok(dictionary) = pages_object.1.as_dict() {
346 let mut dictionary = dictionary.clone();
347
348 // Set new pages count
349 dictionary.set("Count", documents_pages.len() as u32);
350
351 // Set new "Kids" list (collected from documents pages) for "Pages"
352 dictionary.set(
353 "Kids",
354 documents_pages
355 .into_iter()
356 .map(|(object_id, _)| Object::Reference(object_id))
357 .collect::<Vec<_>>(),
358 );
359
360 document
361 .objects
362 .insert(pages_object.0, Object::Dictionary(dictionary));
363 }
364
365 // Build a new "Catalog" with updated fields
366 if let Ok(dictionary) = catalog_object.1.as_dict() {
367 let mut dictionary = dictionary.clone();
368 dictionary.set("Pages", pages_object.0);
369 dictionary.remove(b"Outlines"); // Outlines not supported in merged PDFs
370
371 document
372 .objects
373 .insert(catalog_object.0, Object::Dictionary(dictionary));
374 }
375
376 document.trailer.set("Root", catalog_object.0);
377
378 // Update the max internal ID as wasn't updated before due to direct objects insertion
379 document.max_id = document.objects.len() as u32;
380
381 // Reorder all new Document objects
382 document.renumber_objects();
383
384 // Set any Bookmarks to the First child if they are not set to a page
385 document.adjust_zero_pages();
386
387 // Set all bookmarks to the PDF Object tree then set the Outlines to the Bookmark content map.
388 if let Some(n) = document.build_outline() {
389 if let Ok(Object::Dictionary(dict)) = document.get_object_mut(catalog_object.0) {
390 dict.set("Outlines", Object::Reference(n));
391 }
392 }
393
394 document.compress();
395
396 // Save the merged PDF.
397 // Store file in current working directory.
398 // Note: Line is excluded when running doc tests
399 if false {
400 document.save("merged.pdf").unwrap();
401 }
402
403 Ok(())
404 }
405 ```
406
407 * Decrypt PDF documents
408
409 ```rust
410 use lopdf::Document;
411
412 // Load and decrypt PDF documents with empty password
413 #[cfg(not(feature = "async"))]
414 {
415 // Load an encrypted PDF - automatically attempts decryption with empty password
416 let doc = Document::load("assets/encrypted.pdf").unwrap();
417
418 // Check if the document is encrypted
419 if doc.is_encrypted() {
420 println!("Document is encrypted");
421
422 // The document has been automatically decrypted if the password was empty
423 if doc.encryption_state.is_some() {
424 println!("Successfully decrypted with empty password");
425 }
426 }
427
428 // Access decrypted content
429 let pages = doc.get_pages();
430 println!("Number of pages: {}", pages.len());
431
432 // Extract text from decrypted document
433 let page_numbers: Vec<u32> = pages.keys().cloned().collect();
434 let text = doc.extract_text(&page_numbers).unwrap();
435 println!("Extracted {} characters of text", text.len());
436
437 // Access individual objects
438 for i in 1..=10 {
439 if let Ok(obj) = doc.get_object((i, 0)) {
440 println!("Successfully accessed object ({}, 0)", i);
441 }
442 }
443 }
444
445 #[cfg(feature = "async")]
446 {
447 tokio::runtime::Builder::new_current_thread()
448 .build()
449 .expect("Failed to create runtime")
450 .block_on(async move {
451 // Async version
452 let doc = Document::load("assets/encrypted.pdf").await.unwrap();
453
454 if doc.is_encrypted() {
455 println!("Document is encrypted");
456 if doc.encryption_state.is_some() {
457 println!("Successfully decrypted with empty password");
458 }
459 }
460
461 let pages = doc.get_pages();
462 let page_numbers: Vec<u32> = pages.keys().cloned().collect();
463 let text = doc.extract_text(&page_numbers).unwrap();
464 println!("Extracted {} characters of text", text.len());
465 });
466 }
467 ```
468
469 * Modify PDF document
470
471 ```rust
472 use lopdf::Document;
473
474 // For this example to work a parser feature needs to be enabled
475 #[cfg(not(feature = "async"))]
476 #[cfg(feature = "nom_parser")]
477 {
478 let mut doc = Document::load("assets/example.pdf").unwrap();
479
480 doc.version = "1.4".to_string();
481 doc.replace_text(1, "Hello World!", "Modified text!", None);
482 // Store file in current working directory.
483 // Note: Line is excluded when running tests
484 if false {
485 doc.save("modified.pdf").unwrap();
486 }
487 }
488
489 #[cfg(feature = "async")]
490 #[cfg(feature = "nom_parser")]
491 {
492 tokio::runtime::Builder::new_current_thread()
493 .build()
494 .expect("Failed to create runtime")
495 .block_on(async move {
496 let mut doc = Document::load("assets/example.pdf").await.unwrap();
497
498 doc.version = "1.4".to_string();
499 doc.replace_text(1, "Hello World!", "Modified text!", None);
500 // Store file in current working directory.
501 // Note: Line is excluded when running tests
502 if false {
503 doc.save("modified.pdf").unwrap();
504 }
505 });
506 }
507
508 // For this example to work a parser feature needs to be enabled
509 #[cfg(not(feature = "async"))]
510 #[cfg(feature = "nom_parser")]
511 {
512 let mut doc = Document::load("assets/example.pdf").unwrap();
513
514 doc.version = "1.4".to_string();
515
516 // Replace exact text matches
517 doc.replace_text(1, "Hello World!", "Modified text!", None);
518
519 // Replace partial text matches (new method)
520 let count = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
521 println!("Replaced {} occurrences", count);
522
523 // Store file in current working directory.
524 // Note: Line is excluded when running tests
525 if false {
526 doc.save("modified.pdf").unwrap();
527 }
528 }
529
530 #[cfg(feature = "async")]
531 #[cfg(feature = "nom_parser")]
532 {
533 tokio::runtime::Builder::new_current_thread()
534 .build()
535 .expect("Failed to create runtime")
536 .block_on(async move {
537 let mut doc = Document::load("assets/example.pdf").await.unwrap();
538
539 doc.version = "1.4".to_string();
540
541 // Replace exact text matches
542 doc.replace_text(1, "Hello World!", "Modified text!", None);
543
544 // Replace partial text matches (new method)
545 let count = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
546 println!("Replaced {} occurrences", count);
547
548 // Store file in current working directory.
549 // Note: Line is excluded when running tests
550 if false {
551 doc.save("modified.pdf").unwrap();
552 }
553 });
554 }
555 ```
556
557 * Save PDF with Object Streams (Modern Format)
558
559 Object streams allow multiple non-stream objects to be compressed together, significantly reducing file size.
560
561 ```rust,no_run
562 use lopdf::{Document, SaveOptions};
563
564 #[cfg(not(feature = "async"))]
565 fn main() -> Result<(), Box<dyn std::error::Error>> {
566 // Load existing PDF
567 let mut doc = Document::load("input.pdf")?;
568
569 // Save with modern features (object streams + cross-reference streams)
570 // This typically reduces file size by 11-38%
571 let mut file = std::fs::File::create("output.pdf")?;
572 doc.save_modern(&mut file)?;
573
574 // For more control, use SaveOptions
575 let options = SaveOptions::builder()
576 .use_object_streams(true) // Enable object streams
577 .use_xref_streams(true) // Enable cross-reference streams
578 .max_objects_per_stream(200) // Max objects per stream (default: 100)
579 .compression_level(9) // Compression level 0-9 (default: 6)
580 .build();
581
582 let mut file2 = std::fs::File::create("output_custom.pdf")?;
583 doc.save_with_options(&mut file2, options)?;
584
585 Ok(())
586 }
587
588 #[cfg(feature = "async")]
589 fn main() -> Result<(), Box<dyn std::error::Error>> {
590 // For async feature, you need to use tokio runtime
591 println!("This example requires the async feature to be disabled");
592 Ok(())
593 }
594 ```
595
596 ### Complete Example: Creating and Saving with Object Streams
597
598 ```rust
599 use lopdf::{Document, SaveOptions};
600 use std::fs::File;
601
602 fn main() -> Result<(), Box<dyn std::error::Error>> {
603 // Create or load a document
604 let mut doc = Document::with_version("1.5");
605 // ... add content to document ...
606
607 // Method 1: Quick modern save (recommended)
608 let mut file = File::create("output.pdf")?;
609 doc.save_modern(&mut file)?;
610
611 // Method 2: Custom settings for maximum compression
612 let options = SaveOptions::builder()
613 .use_object_streams(true)
614 .use_xref_streams(true)
615 .max_objects_per_stream(200)
616 .compression_level(9)
617 .build();
618
619 let mut file2 = File::create("output_max_compressed.pdf")?;
620 doc.save_with_options(&mut file2, options)?;
621
622 // Compare file sizes (if traditional file exists)
623 if std::path::Path::new("output_traditional.pdf").exists() {
624 let traditional_size = std::fs::metadata("output_traditional.pdf")?.len();
625 let modern_size = std::fs::metadata("output.pdf")?.len();
626 let reduction = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
627 println!("Size reduction: {:.1}%", reduction);
628 }
629
630 Ok(())
631 }
632 ```
633
634 For more examples, see:
635 - [`examples/object_streams.rs`](examples/object_streams.rs) - Creating PDFs with object streams
636 - [`examples/compress_existing_pdf.rs`](examples/compress_existing_pdf.rs) - Compress existing PDFs
637 - [`examples/analyze_object_streams.rs`](examples/analyze_object_streams.rs) - Analyze object stream usage
638
639 ## Object Streams Support
640
641 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.
642
643 ### Key Benefits
644
645 - **File size reduction**: 11-61% smaller PDFs depending on content
646 - **Modern PDF compliance**: Full PDF 1.5+ specification support
647 - **Backward compatibility**: All existing APIs remain unchanged
648 - **Performance**: <2ms to check 1000 objects for compression eligibility
649
650 ### Creating Object Streams Directly
651
652 ```rust
653 use lopdf::{Object, ObjectStream, dictionary};
654
655 # fn main() -> Result<(), Box<dyn std::error::Error>> {
656 // Create an object stream with custom settings
657 let mut obj_stream = ObjectStream::builder()
658 .max_objects(100) // Maximum objects per stream
659 .compression_level(6) // zlib compression level (0-9)
660 .build();
661
662 // Add objects to the stream
663 obj_stream.add_object((1, 0), Object::Integer(42))?;
664 obj_stream.add_object((2, 0), Object::Name(b"Example".to_vec()))?;
665 obj_stream.add_object((3, 0), Object::Dictionary(dictionary! {
666 "Type" => "Font",
667 "Subtype" => "Type1",
668 "BaseFont" => "Helvetica"
669 }))?;
670
671 // Convert to a stream object
672 let stream = obj_stream.to_stream_object()?;
673 # Ok::<(), Box<dyn std::error::Error>>(())
674 # }
675 ```
676
677 ### Object Eligibility
678
679 Not all objects can be compressed into object streams. The following objects are **excluded**:
680
681 - Stream objects (content streams, image streams, etc.)
682 - Cross-reference streams (Type = XRef)
683 - Object streams themselves (Type = ObjStm)
684 - Encryption dictionary (when referenced by trailer's Encrypt entry)
685 - Objects with generation number > 0
686 - Document catalog in linearized PDFs only
687
688 All other objects, including structural objects (Catalog, Pages, Page) and trailer-referenced objects (except encryption), can be compressed.
689
690 ### Cross-reference Streams
691
692 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.
693
694 ### SaveOptions Reference
695
696 The `SaveOptions` builder provides fine-grained control over PDF compression:
697
698 ```rust
699 use lopdf::SaveOptions;
700
701 let options = SaveOptions::builder()
702 .use_object_streams(true) // Enable object streams (default: false)
703 .use_xref_streams(true) // Enable xref streams (default: false)
704 .max_objects_per_stream(200) // Max objects per stream (default: 100)
705 .compression_level(9) // zlib level 0-9 (default: 6)
706 .build();
707 ```
708
709 ## PDF Decryption Support
710
711 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.
712
713 ### Key Features
714
715 - **Automatic decryption**: PDFs encrypted with empty passwords are automatically decrypted on load
716 - **Object stream support**: Handles encrypted PDFs containing compressed object streams
717 - **Transparent access**: Once decrypted, all document methods work normally
718 - **Preservation of structure**: Document structure and content remain intact after decryption
719
720 ### How It Works
721
722 When loading an encrypted PDF, lopdf:
723 1. Detects encryption via the `Encrypt` entry in the trailer
724 2. Extracts raw object bytes before parsing
725 3. Attempts authentication with an empty password
726 4. Decrypts all objects if authentication succeeds
727 5. Processes compressed objects from object streams
728
729 ### Example: Working with Encrypted PDFs
730
731 ```rust
732 use lopdf::Document;
733
734 #[cfg(not(feature = "async"))]
735 fn main() -> Result<(), Box<dyn std::error::Error>> {
736 // Load an encrypted PDF - automatically attempts decryption
737 let doc = Document::load("assets/encrypted.pdf")?;
738
739 // Check encryption status
740 if doc.is_encrypted() {
741 println!("Document is encrypted");
742
743 // Check if decryption was successful
744 if doc.encryption_state.is_some() {
745 println!("Successfully decrypted");
746
747 // Now you can work with the document normally
748 let pages = doc.get_pages();
749 println!("Pages: {}", pages.len());
750
751 // Extract text
752 let page_nums: Vec<u32> = pages.keys().cloned().collect();
753 let text = doc.extract_text(&page_nums)?;
754 println!("Text length: {} chars", text.len());
755
756 // Access objects
757 for i in 1..=10 {
758 if let Ok(_) = doc.get_object((i, 0)) {
759 println!("Object ({}, 0) accessible", i);
760 }
761 }
762 } else {
763 println!("Decryption failed - password required");
764 }
765 }
766
767 Ok(())
768 }
769
770 #[cfg(feature = "async")]
771 #[tokio::main]
772 async fn main() -> Result<(), Box<dyn std::error::Error>> {
773 // Load an encrypted PDF - automatically attempts decryption
774 let doc = Document::load("assets/encrypted.pdf").await?;
775
776 // Check encryption status
777 if doc.is_encrypted() {
778 println!("Document is encrypted");
779
780 // Check if decryption was successful
781 if doc.encryption_state.is_some() {
782 println!("Successfully decrypted");
783
784 // Now you can work with the document normally
785 let pages = doc.get_pages();
786 println!("Pages: {}", pages.len());
787
788 // Extract text
789 let page_nums: Vec<u32> = pages.keys().cloned().collect();
790 let text = doc.extract_text(&page_nums)?;
791 println!("Text length: {} chars", text.len());
792
793 // Access objects
794 for i in 1..=10 {
795 if let Ok(_) = doc.get_object((i, 0)) {
796 println!("Object ({}, 0) accessible", i);
797 }
798 }
799 } else {
800 println!("Decryption failed - password required");
801 }
802 }
803
804 Ok(())
805 }
806 ```
807
808 ### Limitations
809
810 - Currently only supports PDFs encrypted with empty passwords
811 - Password-protected PDFs require manual authentication (use `authenticate_password` method)
812 - Some encryption algorithms may not be fully supported
813
814 For more examples, see:
815 - [`examples/test_decryption.rs`](examples/test_decryption.rs) - Testing decryption functionality
816 - [`examples/verify_decryption.rs`](examples/verify_decryption.rs) - Comprehensive decryption verification
817 - [`tests/decryption.rs`](tests/decryption.rs) - Decryption test suite
818
819 ## FAQ
820
821 * Why does the library keep everything in memory as high-level objects until finally serializing the entire document?
822
823 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.
824 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.
825 The resulting PDF file is smaller for distribution and faster for PDF consumers to process.
826
827 Producing is a one-time effort, while consuming is many more.
828
829 * How do object streams affect memory usage?
830
831 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.
832
833 * What PDF versions support object streams?
834
835 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.
836
837 * Can I analyze existing PDFs to see if they use object streams?
838
839 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.
840
841 ## License
842
843 lopdf is available under the MIT license, with the exception of the Montserrat font.