Encryption and permissions
Open password-protected PDFs, encrypt with AES-256 and permissions, remove passwords, and stamp watermarks, headers and Bates numbers with NexPDF for Rust.
License module
Encrypting, removing passwords, watermarks, headers, footers and Bates numbering need the security
module (Startup tier and above). Opening encrypted files and reading their security settings work
without a key.
Open an encrypted PDF
use nexpdf_sdk::Document;
fn main() -> nexpdf_sdk::Result<()> {
let doc = match Document::open_with_password("protected.pdf", "secret") {
Ok(doc) => doc,
Err(e) => {
eprintln!("{e}"); // nexpdf: password required, or nexpdf: incorrect password
return Err(e);
}
};
let info = doc.security_json_value()?; // `serde` feature; or security_json()
println!("{} {} {} {}", info["encrypted"], info["owner"], info["print"], info["copy"]);
Ok(())
}The user (open) password or the owner password both work. RC4, AES-128 and AES-256 files are supported.
security_json() reports encrypted, revision, owner (opened with owner access) and the
permissions print, modify, copy, annotate, fill_forms and assemble.
Encrypt with AES-256
doc.encrypt_aes256("user-password", "owner-password")?;
doc.save("encrypted.pdf")?;An empty user password lets anyone open the file while the owner password still protects the permissions.
Set permissions
encrypt_with_permissions(user_pw, owner_pw, permissions) takes a u32 bit mask of what users
without the owner password may do:
| Flag | Value |
|---|---|
| 1 | |
| Modify | 2 |
| Copy text and images | 4 |
| Annotate | 8 |
| Fill forms | 16 |
| Assemble (insert, rotate, delete pages) | 32 |
const PRINT: u32 = 1;
const FILL_FORMS: u32 = 16;
doc.encrypt_with_permissions("", "owner-password", PRINT | FILL_FORMS)?;
doc.save("print-and-fill-only.pdf")?;Remove a password
let mut doc = Document::open_with_password("encrypted.pdf", "owner-password")?;
doc.remove_password(None)?; // or pass the owner password here
doc.save("decrypted.pdf")?;Watermarks, headers, footers and Bates numbers
doc.add_watermark("CONFIDENTIAL")?;
doc.add_header_footer("Acme, Lda", "Page {page} of {total}", 9.0)?; // font size 0 = default
doc.add_bates("ACME-", 1, 6)?; // ACME-000001, ACME-000002, ...
doc.remove_watermarks()?; // removes NexPDF watermarks