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, EncryptionOptions};
fn main() -> pdfluent::Result<()> {
let mut doc = PdfDocument::open("report.pdf")?;
// User password: required to open the file
// Owner password: required to change permissions
let opts = EncryptionOptions::aes256("owner-pw-123", "user-pw-456");
doc.encrypt(opts)?;
doc.save("report-protected.pdf")?;
println!("Password protection applied.");
Ok(())
}The encryption feature includes AES-128 and AES-256 support.
# Cargo.toml
[dependencies]
pdfluent = { version = "0.9", features = ["encryption"] }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::EncryptionOptions;
// Both passwords set - readers must enter user-pw to open
let opts = EncryptionOptions::aes256("owner-pw-123", "user-pw-456");
// Owner password only - file opens without a password, but editing is restricted
let opts = EncryptionOptions::aes256("owner-pw-123", "");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(pdfluent::Error::PasswordRequired) => {
println!("Correct: file requires a password to open.");
}
Ok(_) => println!("Warning: file opened without password."),
Err(e) => eprintln!("Unexpected error: {}", e),
}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.