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 Android.
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
NexPdfDocument has no password parameter. Open encrypted files with
NexPdfJni.openBytesWithPassword, which returns a native handle (0 on failure). Use it with the
NexPdfJni methods and free it with NexPdfJni.free:
import com.nexdevit.nexpdf.NexPdfJni
val h = NexPdfJni.openBytesWithPassword(bytes, "secret")
if (h == 0L) {
Log.e("NexPDF", NexPdfJni.lastError()) // "password required" or "incorrect password"
return
}
try {
val info = JSONObject(NexPdfJni.securityJson(h))
Log.i("NexPDF", "${info.optBoolean("encrypted")} ${info.optBoolean("owner")} ${info.optBoolean("print")}")
val text = NexPdfJni.extractPageText(h, 0)
} finally {
NexPdfJni.free(h)
}The user (open) password or the owner password both work. RC4, AES-128 and AES-256 files are
supported. securityJson reports encrypted, revision, owner (opened with owner access) and
the permissions print, modify, copy, annotate, fill_forms and assemble.
Encrypt with AES-256
NexPdfJni.encryptAes256(doc.handle(), "user-password", "owner-password")
val encrypted = doc.saveBytes()An empty user password lets anyone open the file while the owner password still protects the permissions.
Set permissions
encryptWithPermissions(handle, userPw, ownerPw, permissions) takes a bit mask of what users
without the owner password may do. NexPdfJni has a constant for each flag:
| Flag | Constant | Value |
|---|---|---|
PERM_PRINT | 1 | |
| Modify | PERM_MODIFY | 2 |
| Copy text and images | PERM_COPY | 4 |
| Annotate | PERM_ANNOTATE | 8 |
| Fill forms | PERM_FILL_FORMS | 16 |
| Assemble (insert, rotate, delete pages) | PERM_ASSEMBLE | 32 |
NexPdfJni.encryptWithPermissions(doc.handle(), "", "owner-password",
NexPdfJni.PERM_PRINT or NexPdfJni.PERM_FILL_FORMS)
val printAndFillOnly = doc.saveBytes()Remove a password
val h = NexPdfJni.openBytesWithPassword(encrypted, "owner-password")
try {
NexPdfJni.removePassword(h, null) // or pass the owner password here
val decrypted = NexPdfJni.saveBytes(h)
} finally {
NexPdfJni.free(h)
}Watermarks, headers, footers and Bates numbers
val h = doc.handle()
NexPdfJni.addWatermark(h, "CONFIDENTIAL")
NexPdfJni.addHeaderFooter(h, "Acme, Lda", "Page {page} of {total}", 9.0) // font size 0 = default
NexPdfJni.addBates(h, "ACME-", 1, 6) // ACME-000001, ACME-000002, ...
NexPdfJni.removeWatermarks(h) // removes NexPDF watermarks