Expand description
§PDFium-rs
A modern, streamlined Rust interface to the PDFium C library, designed for simplicity and thread safety in interactive applications. PDFium is Google’s PDF library developed for (and used in) the Chromium and Chrome web browsers.
§Features
- Thread-safe static library access - Initialize once, use everywhere
- Lifetime-free API - No complex lifetime management for documents, pages, and bitmaps
- Access to C API - Safe access to the full C API. All 440+ functions are available, fully documented
- Idiomatic Rust abstractions - An idiomatic high-level Rust interface to the most frequently used features
- Renderer selection - Select either
Skia
orAGG
(Anti-Grain Geometry) as renderer for PDFium
§Why This Crate?
While existing PDFium bindings for Rust are available, this crate takes a different approach focused on ease of use and thread safety:
§Thread-Safe Static Access
This library uses a modern, static, and thread-safe initialization pattern with parking_lot::ReentrantMutex
. On first use, it checks for the availability of the PDFium dynamic library on your system or in a specified directory, and stores the library reference statically for the application’s lifetime. This eliminates the need for complex library management and prevents deadlocks when used multiple times in the same thread.
§No Lifetime Complexity
Unlike other implementations, this crate doesn’t impose lifetimes on structs representing documents, pages, bitmaps, and other structures. This makes integration into your application much simpler - you can store these objects wherever you need them without fighting the borrow checker. They are even clonable. This makes it ideal for interactive use cases, such as PDF viewers, editors, and other real-time applications.
§Access to the full C API without unsafe
Functions
While most users will be using the high-level idiomatic Rust abstractions, PDFium-rs does provide safe public access to the entire C API with full documentation. Unsafe pointers to C structures and memory have been transparently replaced with their Rust counterparts. This feature makes it also possible to seamlessly mix idiomatic Rust functions with the C API functions.
§Used by MView6
PDFium-rs serves as one of the two PDF engines behind MView6, a PDF and photo viewer written in Rust and GTK4 by the same author. With a single keypress, you can switch engines and compare the rendering quality differences between mupdf and PDFium.
§Quick Start
use pdfium::*;
struct App {
doc: PdfiumDocument,
}
impl App {
pub fn new(filename: &str) -> PdfiumResult<Self> {
Ok(App {
doc: PdfiumDocument::new_from_path(filename, None)?,
})
}
pub fn render_to_file(&self, filename: &str, index: i32) -> PdfiumResult<()> {
let page = self.doc.page(index)?;
let config = PdfiumRenderConfig::new().with_height(1080);
let bitmap = page.render(&config).unwrap();
bitmap.save(filename, image::ImageFormat::Png)
}
}
fn main() -> PdfiumResult<()> {
let app = App::new("resources/groningen.pdf")?;
app.render_to_file("groningen-page-1-rust.png", 0)
}
§Lifetimes
The quick start example already shows PDFium-rs is easy with lifetimes: a PdfiumDocument
can be stored in a struct without lifetime issues. The same applies to all other PDFium-rs structs.
They are also clonable and the library will track their usage and close when possible, as shown below:
use pdfium::*;
let document = PdfiumDocument::new_from_path("resources/groningen.pdf", None).unwrap();
let page = document.page(0).unwrap();
drop(document); // Demonstrate that the page can be used after the document is dropped.
let config = PdfiumRenderConfig::new().with_height(1080);
let bitmap = page.render(&config).unwrap();
bitmap.save("groningen-drop-demo.jpg", image::ImageFormat::Jpeg);
§Using the PDFium C API
This is the same example as the quick start, but now using the C API of PDFium directly.
- Using the C API is safe, no
unsafe
code blocks in your code - Access the C API through
lib
ortry_lib
- You can mix idiomatic Rust with C, shown here with the
bitmap.save
operation
use pdfium::*;
struct App {
doc: PdfiumDocument,
}
impl App {
pub fn new(filename: &str) -> PdfiumResult<Self> {
Ok(App {
doc: PdfiumDocument::new_from_path(filename, None)?,
})
}
pub fn render_to_file(&self, filename: &str, index: i32) -> PdfiumResult<()> {
let page = lib().FPDF_LoadPage(&self.doc, index)?;
let mut left = 0.0;
let mut bottom = 0.0;
let mut right = 0.0;
let mut top = 0.0;
lib().FPDFPage_GetMediaBox(&page, &mut left, &mut bottom, &mut right, &mut top)?;
let height = 1080;
let scale = height as f32 / (top - bottom);
let width = ((right - left) * scale) as i32;
let matrix = pdfium_types::FS_MATRIX {
a: scale,
b: 0.0,
c: 0.0,
d: scale,
e: 0.0,
f: 0.0,
};
let bitmap = lib().FPDFBitmap_Create(width, height, 1)?;
lib().FPDFBitmap_FillRect(&bitmap, 0, 0, width, height, 0xffffffff)?;
let clipping = pdfium_types::FS_RECTF {
left: 0.0,
top: height as f32,
right: width as f32,
bottom: 0.0,
};
lib().FPDF_RenderPageBitmapWithMatrix(&bitmap, &page, &matrix, &clipping, 0);
bitmap.save(filename, image::ImageFormat::Png)?;
Ok(())
}
}
fn main() -> PdfiumResult<()> {
let app = App::new("resources/groningen.pdf")?;
app.render_to_file("groningen-page-1-c.png", 0)
}
§More examples
You can find more information on how to use PDFium-rs in the examples/
directory.
§Installation
Add this to your Cargo.toml
:
[dependencies]
pdfium = "0.9.5" # Check crates.io for the latest version
For the latest version, visit crates.io or use cargo search pdfium
.
§Dynamic Library Requirements
PDFium-rs requires the PDFium dynamic library to be available on your system:
- Linux:
libpdfium.so
- Windows:
pdfium.dll
- macOS:
libpdfium.dylib
§Obtaining PDFium Libraries
Pre-built libraries for all major platforms are available from: https://github.com/bblanchon/pdfium-binaries/releases
Choose the appropriate build for your target platform and architecture (x64, arm64, etc.).
§Library Installation
§Option 1: System Installation (Recommended for Linux/macOS)
- Linux: Place in
/usr/lib/
,/usr/local/lib/
, or/usr/lib/your_app/
- macOS: Place in
/usr/local/lib/
or/opt/homebrew/lib/
- Use
set_library_location
to specify custom paths
§Option 2: Application Bundle (Recommended for Windows)
- Windows: Place
pdfium.dll
in the same directory as your executable
§Option 3: Custom Location
use pdfium::*;
// Set custom library path before first use
set_library_location("/path/to/your/pdfium/library/");
// Your application code...
let doc = PdfiumDocument::new_from_path("document.pdf", None);
§Renderer Selection: Skia
or AGG
PDFium currently supports two rendering backends. You can select Skia
over AGG
(Anti-Grain Geometry) using the set_use_skia
function:
use pdfium::*;
// Use Skia renderer (must be called before first PDFium usage)
set_use_skia(true);
// Your application code...
let doc = PdfiumDocument::new_from_path("document.pdf", None);
§Supported Platforms
- Linux: x86_64, aarch64 (ARM64)
- Windows: x86_64, x86 (32-bit)
- macOS: x86_64, aarch64 (Apple Silicon)
All platforms require their respective PDFium dynamic libraries.
§Troubleshooting
§Library Loading Errors
/// Error loading or initializing the PDFium library
PdfiumError::LibraryError(String)
§Solutions
- Verify the PDFium library is in the correct location
- Check that the library architecture matches your application (64-bit vs 32-bit)
- On Linux, verify library dependencies with
ldd libpdfium.so
- Use
set_library_location
to specify the exact path - Ensure file permissions allow reading the library
§Windows-Specific Issues
- Install Visual C++ Redistributable if you encounter DLL loading errors
- Ensure
pdfium.dll
is in your PATH or application directory
§macOS-Specific Issues
- You may need to remove quarantine attributes:
xattr -d com.apple.quarantine libpdfium.dylib
- For unsigned libraries, you might need to approve them in System Preferences > Security & Privacy
§Runtime Errors
This might indicate an incompatible PDFium library version. Try downloading a different build from the pdfium-binaries releases.
§Getting Help
If you encounter issues not covered here:
- Check the GitHub Issues
- Verify your PDFium library version compatibility
- Include your platform, Rust version, and PDFium library source when reporting issues
§Current Status
This crate is actively being developed and already implements a safe Rust interface to the full C API (all 440+ fuctions).
The idomatic abstraction is focused on a subset of PDFium’s functionality. While it covers the core rendering and document manipulation features needed for most interactive applications, it doesn’t (yet) provide the complete feature set.
§What’s Available
- Document loading and basic properties
- Page rendering with customizable parameters
- Bitmap handling and export
- Thread-safe access patterns
- Full safe C API access
§Planned Features
- Text extraction and search
- Form field support
- Annotation handling
- Additional rendering options
- Security and encryption support
- Bookmarks and navigation
§Requirements
- Rust 1.80 or later
- PDFium dynamic library (see installation instructions)
§Contributing
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
After cloning the repository, install the git hooks:
./scripts/install-hooks.sh
§License
PDFium-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Modules§
- pdfium_
constants - Constants used by the PDFium C library
- pdfium_
types - Types (structures and typedefs) used by the PDFium C library
Structs§
- Pdfium
- Safe Rust wrapper around the complete PDFium C API
- Pdfium
Action - Rust interface to FPDF_ACTION
- Pdfium
Annotation - Rust interface to FPDF_ANNOTATION
- Pdfium
Attachment - Rust interface to FPDF_ATTACHMENT
- Pdfium
Availability - Rust interface to FPDF_AVAIL
- Pdfium
Bitmap - Rust interface to FPDF_BITMAP
- Pdfium
Bookmark - Rust interface to FPDF_BOOKMARK
- Pdfium
Clip Path - Rust interface to FPDF_CLIPPATH
- Pdfium
Color - Rust interface to PDFium colors
- Pdfium
Destination - Rust interface to FPDF_DEST
- Pdfium
Document - Rust interface to FPDF_DOCUMENT
- Pdfium
Font - Rust interface to FPDF_FONT
- Pdfium
Form - Rust interface to FPDF_FORMHANDLE
- Pdfium
Glyph Path - Rust interface to FPDF_GLYPHPATH
- Pdfium
Javascript Action - Rust interface to FPDF_JAVASCRIPT_ACTION
- Pdfium
Link - Rust interface to FPDF_LINK
- Pdfium
Matrix - Rust interface to FS_MATRIX
- Pdfium
Page - Rust interface to FPDF_PAGE
- Pdfium
Page Boundaries - Rust interface to the boundary boxes of a page
- Pdfium
Page Link - Rust interface to FPDF_PAGELINK
- Pdfium
Page Object - Rust interface to FPDF_PAGEOBJECT
- Pdfium
Page Object Mark - Rust interface to FPDF_PAGEOBJECTMARK
- Pdfium
Page Range - Rust interface to FPDF_PAGERANGE
- Pdfium
Path Segment - Rust interface to FPDF_PATHSEGMENT
- Pdfium
Reader - Enables Rust based readers (implementing
Read
+Seek
) with PDFium. - Pdfium
Rect - Rust interface to FS_RECTF
- Pdfium
Render Config - Configuration for PDF page rendering operations.
- Pdfium
Render Flags - Flags controlling the PDFium rendering behavior.
- Pdfium
Search - Rust interface to FPDF_SCHHANDLE
- Pdfium
Search Flags - A bitflag type representing various search options for PDF text searching.
- Pdfium
Signature - Rust interface to FPDF_SIGNATURE
- Pdfium
Struct Element - Rust interface to FPDF_STRUCTELEMENT
- Pdfium
Struct Element Attr - Rust interface to FPDF_STRUCTELEMENT_ATTR
- Pdfium
Struct Element Attr Value - Rust interface to FPDF_STRUCTELEMENT_ATTR_VALUE
- Pdfium
Struct Tree - Rust interface to FPDF_STRUCTTREE
- Pdfium
Text Page - Rust interface to FPDF_TEXTPAGE
- PdfiumX
Object - Rust interface to FPDF_XOBJECT
Enums§
- Pdfium
Bitmap Format - The pixel format of the backing buffer of a PdfiumBitmap.
- Pdfium
Error - Enumerations of errors that can occur in PDFium and PDFium-rs
Functions§
- lib
- Access to the PDFium dynamic library with thread-safe reentrant locking
- set_
library_ location - Set a specific location (directory) for the PDFium dynamic library (so/dll/dylib)
- set_
use_ skia - Enable the use of the Skia renderer. Default renderer is AGG (Aggregated Graphics).
- try_lib
- Access to the PDFium dynamic library with thread-safe reentrant locking
Type Aliases§
- Pdfium
Result - Alias for
Result<T, PdfiumError>