How-to guides/Security & Encryption

Encrypt a PDF with a password in Rust

Protect a PDF with a user password and an owner password. Set 128-bit RC4 or 256-bit AES encryption and fine-grained permission flags.

rust
use pdfluent::{PdfDocument, EncryptOptions, PdfPermissions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = PdfDocument::open("report.pdf")?;

    let opts = EncryptOptions::aes256()
        .user_password("open123")
        .owner_password("owner_secret")
        .permissions(PdfPermissions::all_except_edit());

    doc.encrypt(&opts)?;
    doc.save("report_protected.pdf")?;
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the PDF

Open the document you want to protect. Use a mutable binding.

rust
use pdfluent::PdfDocument;

let mut doc = PdfDocument::open("report.pdf")?;
2

Choose the encryption algorithm

EncryptOptions::aes256() uses AES-256, which is the current best practice. Use EncryptOptions::aes128() if you need compatibility with older readers.

rust
use pdfluent::EncryptOptions;

let opts = EncryptOptions::aes256();
3

Set user and owner passwords

The user password is required to open the document. The owner password unlocks all permissions. If you omit user_password, the document opens without a password but still enforces permission flags.

rust
let opts = opts
    .user_password("open_document_2025")
    .owner_password("full_access_secret");
4

Configure permissions

PdfPermissions lets you allow or deny printing, copying text, modifying content, and filling forms.

rust
use pdfluent::PdfPermissions;

let perms = PdfPermissions::default()
    .allow_printing(true)
    .allow_copy_text(false)
    .allow_modify(false)
    .allow_fill_forms(true);

let opts = opts.permissions(perms);
5

Encrypt and save

Call encrypt() then save() to write the protected file.

rust
doc.encrypt(&opts)?;
doc.save("report_protected.pdf")?;

Notes and tips

  • AES-256 requires PDF 1.7 or later. If you need compatibility with very old readers, use RC4-128 (PDF 1.4).
  • The owner password controls the permission flags. Without it, even the software that created the PDF cannot bypass the restrictions.
  • Encryption does not compress the document. The file size stays roughly the same.
  • PDF/A documents must not be encrypted. Remove encryption before validating for PDF/A compliance.

Why PDFluent for this

Pure Rust

No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.

Memory safe

Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.

Runs anywhere

Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.

Frequently asked questions