Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

lopdf

> 编程语言
Open source

A Rust library for PDF document manipulation.

2.2K stars0 likes0 views
WebsiteGitHub

About

A Rust library for PDF document manipulation.

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. The PDF 2.0 specification is available here.

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
…
  • Merge PDF documents
…
  • Decrypt PDF documents
…
  • Modify PDF document
…
  • Save PDF with Object Streams (Modern Format)

Object streams allow multiple non-stream objects to be compressed together, significantly reducing file size.

…

Complete Example: Creating and Saving with Object Streams

…

For more examples, see:

  • examples/object_streams.rs - Creating PDFs with object streams
  • examples/compress_existing_pdf.rs - Compress existing PDFs
  • 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

…

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:

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

…

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 - Testing decryption functionality
  • examples/verify_decryption.rs - Comprehensive decryption verification
  • 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.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustpdf-documentrustrust-library

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言