Protect a PDF with a password so readers must enter it to open the file, or set an owner password to restrict editing.
use pdfluent::{PdfDocument, EncryptOptions};
fn main() -> pdfluent::Result<()> {
let mut doc = PdfDocument::open("invoice.pdf")?;
doc.encrypt(EncryptOptions::aes256().with_user_password("s3cret"))?;
doc.save("invoice-protected.pdf")?;
Ok(())
}The encryption feature includes AES-128 and AES-256 support.
# Cargo.toml
[dependencies]
pdfluent = "1.0.0-beta.8"Open the PDF you want to protect. If it is already encrypted, open it with the current owner password first.
use pdfluent::PdfDocument;
let mut doc = PdfDocument::open("report.pdf")?;The first argument to aes256() is the owner password. The second is the user password. Set the user password to an empty string to allow opening without a password while still restricting permissions.
use pdfluent::EncryptOptions;
// Both passwords set - readers must enter user-pw to open
let opts = EncryptOptions::aes256().with_owner_password("owner-pw-123").with_user_password("user-pw-456");
// Owner password only - file opens without a password, but editing is restricted
let opts = EncryptOptions::aes256().with_owner_password("owner-pw-123").with_user_password("");doc.encrypt() modifies the in-memory document. The protection is written to disk on save.
doc.encrypt(opts)?;
doc.save("report-protected.pdf")?;
println!("Saved report-protected.pdf");Re-open the saved file and confirm it requires a password.
let result = PdfDocument::open("report-protected.pdf");
match result {
Err(_) => println!("Correct: file requires a password to open."),
Ok(_) => println!("Warning: file opened without a password."),
}No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.
Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.
Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.