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 iOS (Swift).
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
import NexPdf
let doc: NexPdfDocument
do {
doc = try NexPdfDocument.open(url: url, password: "secret")
} catch let error as NexPdfError {
print(error.message) // "password required" or "incorrect password"
return
}The user (open) password or the owner password both work. RC4, AES-128 and AES-256 files are
supported. In the reader, NexPdfReaderController.open throws
OpenError.passwordRequired so you can ask the user.
let info = NexPdf.json(try doc.securityJson()) as? [String: Any]
print(info?["encrypted"] ?? false, info?["owner"] ?? false, info?["print"] ?? false, info?["copy"] ?? false)securityJson() reports encrypted, revision, owner (opened with owner access) and the
permissions print, modify, copy, annotate, fill_forms and assemble.
Encrypt with AES-256
try doc.encryptAes256(userPw: "user-password", ownerPw: "owner-password")
try doc.write(to: encryptedURL)An empty user password lets anyone open the file while the owner password still protects the permissions.
Set permissions
encryptWithPermissions(userPw:ownerPw:permissions:) takes a 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 |
let printFlag: UInt32 = 1, fillFormsFlag: UInt32 = 16
try doc.encryptWithPermissions(userPw: "", ownerPw: "owner-password", permissions: printFlag | fillFormsFlag)
try doc.write(to: outputURL)Remove a password
let doc = try NexPdfDocument.open(url: encryptedURL, password: "owner-password")
try doc.removePassword() // or pass the owner password here
try doc.write(to: decryptedURL)Watermarks, headers, footers and Bates numbers
try doc.addWatermark(text: "CONFIDENTIAL")
try doc.addHeaderFooter(header: "Acme, Lda", footer: "Page {page} of {total}", fontSize: 9) // 0 = default size
try doc.addBates(prefix: "ACME-", start: 1, digits: 6) // ACME-000001, ...
try doc.removeWatermarks() // removes NexPDF watermarks