1. Products
  2.   PDF
  3.   Rust
  4.   lopdf

lopdf

 
 

Open Source Rust Library for PDF Documents

Read, Write, Merge, Modify, Decrypt & Compress PDF Files with Object Streams via Rust API.

What is lopdf?

lopdf is a high-performance, open source Rust library for comprehensive PDF document manipulation. It enables developers to create, read, modify, merge, and decrypt PDF files directly from Rust applications. The library supports modern PDF features including object streams, cross-reference streams, and encryption handling, ensuring efficient file processing and reduced storage overhead. With a clean, idiomatic Rust API, lopdf provides full control over PDF structure while maintaining compatibility with the PDF 1.7 and 2.0 specifications.

Designed for reliability and speed, lopdf processes PDFs entirely in memory before serialization, enabling precise length calculations and smaller output files. It supports asynchronous loading via Tokio, automatic decryption of empty-password PDFs, and advanced compression techniques. The library includes extensive examples for common tasks such as text replacement, bookmark management, and modern PDF saving. Whether you're building document automation tools, report generators, or PDF processing pipelines, lopdf delivers a robust foundation for production-grade applications.

Previous Next

Getting Started with lopdf

To start using lopdf, add it to your Cargo.toml with lopdf = "0.1". The library is available on crates.io and supports modern Rust features including async via Tokio. You can install it via cargo add lopdf or manually edit dependencies. For detailed documentation, visit the [lopdf](https://github.com/J-F-Liu/lopdf) repository. The library requires Rust 1.85 or later and supports optional features like chrono, rayon, and serde for enhanced functionality.

Install lopdf via Cargo

[dependencies]
lopdf = "0.1"

Create PDF Documents from Scratch

lopdf enables developers to programmatically create PDF documents with full control over structure and content. You can define pages, fonts, resources, and content streams using intuitive Rust APIs. The library supports modern PDF features like object streams and cross-reference streams for optimized file size. With helper macros like `dictionary!`, building complex PDF structures becomes straightforward. This makes lopdf ideal for generating reports, invoices, certificates, and other dynamic documents directly from Rust applications without external dependencies.

How to Create a Simple PDF with Text via Rust?

use lopdf::dictionary;
use lopdf::{Document, Object, Stream};
use lopdf::content::{Content, Operation};

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,
});
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()],
};
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();
doc.save("example.pdf").unwrap();

Merge Multiple PDF Documents

Merging PDFs is a core capability of lopdf, allowing you to combine multiple documents into a single cohesive file. The library handles object ID renumbering, page tree reconstruction, and catalog updates automatically. You can merge documents while preserving bookmarks, page attributes, and content integrity. This feature is particularly useful for building document aggregation tools, report consolidation systems, and workflow automation pipelines. lopdf ensures that merged PDFs remain compliant with PDF specifications and maintain optimal structure for downstream processing.

How to Merge Multiple PDFs into One Document via Rust?

use lopdf::dictionary;
use std::collections::{BTreeMap, HashSet};
use lopdf::content::{Content, Operation};
use lopdf::{Document, Dictionary, Error, Object, ObjectId, Stream, Bookmark};

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
}

// [Full merge logic omitted for brevity — see documentation for complete implementation]

Decrypt PDF Documents Automatically

lopdf includes robust support for decrypting PDF documents, especially those protected with empty passwords — a common scenario for many publicly shared files. The library automatically detects encryption and attempts decryption during document loading, making it transparent for developers. Once decrypted, all document operations work normally, including text extraction, modification, and saving. This feature is critical for building document processing pipelines that handle diverse input sources without manual intervention or external tools.

How to Load and Decrypt a PDF with Empty Password via Rust?

use lopdf::Document;

#[cfg(not(feature = "async"))]
fn main() -> Result<(), Box> {
    let doc = Document::load("assets/encrypted.pdf")?;
    
    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();
    println!("Number of pages: {}", pages.len());
    
    let page_numbers: Vec = pages.keys().cloned().collect();
    let text = doc.extract_text(&page_numbers)?;
    println!("Extracted {} characters of text", text.len());
    
    Ok(())
}

Modify and Compress PDF Files

lopdf provides powerful tools for modifying existing PDFs, including text replacement, version updates, and content adjustments. With parser features enabled, you can perform exact or partial text replacements across pages. The library also supports modern compression techniques like object streams and cross-reference streams, reducing file sizes by up to 61%. Using `save_modern()` or `save_with_options()`, developers gain fine-grained control over compression levels and stream configurations, making lopdf suitable for both archival and high-performance use cases.

How to Replace Text and Save with Object Streams via Rust?

use lopdf::Document;

#[cfg(not(feature = "async"))]
#[cfg(feature = "nom_parser")]
fn main() -> Result<(), Box> {
    let mut doc = Document::load("assets/example.pdf")?;
    
    doc.version = "1.4".to_string();
    doc.replace_text(1, "Hello World!", "Modified text!", None);
    
    // Save with modern compression
    let mut file = std::fs::File::create("output.pdf")?;
    doc.save_modern(&mut file)?;
    
    Ok(())
}
 English