Skip to Content
NexPDF

Error handling

How NexPDF for Android reports failures - the exceptions of NexPdfDocument, the return values and lastError of NexPdfJni, license codes, engine messages and untrusted files.

English

NexPDF for Android reports failures in two ways:

  • NexPdfDocument throws when a document cannot be opened or is used after close().
  • NexPdfJni methods never throw. A failure returns a failure value, and NexPdfJni.lastError() gives the engine's reason on the same thread.

Exceptions

ExceptionThrown when
IllegalArgumentExceptionNexPdfDocument.openBytes, openEbook, openImage, openOffice, fromHtml, fromDocxTemplate or fromHtmlTemplate could not open or create the document. The message is the engine's error; NexPdfDocument.isPasswordError(e) is true for password required and incorrect password
IllegalStateExceptionhandle() (and so every method of NexPdfDocument) was called after close(): document is closed
UnsatisfiedLinkErrorThe first use of NexPdfJni could not load libnexpdf_jni.so or libnexpdf_ffi.so, for example on an ABI the AAR does not include. Later uses throw NoClassDefFoundError
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni

try {
    NexPdfDocument.openBytes(upload).use { doc ->
        if (!NexPdfJni.addWatermark(doc.handle(), "CONFIDENTIAL")) {
            Log.w("NexPDF", "watermark failed: ${NexPdfJni.lastError()}")
            return
        }
        out.writeBytes(doc.saveBytes())
    }
} catch (e: IllegalArgumentException) {
    Log.w("NexPDF", "NexPDF could not open the upload: ${e.message}")
}

Return values of NexPdfJni

Return typeFailure value
boolean (actions such as rotatePage, fillFormField)false
int counts (such as flattenForms, redactMatches, insertImagePages)-1
long handles (openBytes, openBytesWithPassword, extractPages, openOffice)0
String (JSON and text)""
byte[] (PNG, PDF, Office files)an empty array

Read NexPdfJni.lastError() right after a call that returned a failure value, on the same thread. Errors are tracked per thread, and a successful call does not always clear the previous error, so an error message alone does not mean the last call failed. An empty string or array can also be a real result, for example the text of a scanned page with no text layer.

val png = NexPdfJni.renderPagePng(h, 0, 144.0)
if (png.isEmpty()) error("render failed: ${NexPdfJni.lastError()}")

Two rules protect the process, because handles are native pointers:

  • Never use a handle after NexPdfJni.free(handle) or doc.close(). NexPdfDocument checks this and throws; a raw long handle does not.
  • Pass null only where a method says it accepts it (for example the values of setMetadata or the pages of removePageBackground). Some methods hand their arguments straight to native code.

Common engine messages

MessageCauseWhat to do
password requiredThe file is encrypted and no password was givenAsk for the password and open with NexPdfJni.openBytesWithPassword
incorrect passwordThe password matches neither the user nor the owner passwordAsk again
no license activated: '<module>' requires a NexPDF license keyThe call needs a module and no key is activeCall NexPdfLicense.initialize in Application.onCreate(); see Running without a key
the active license does not include the '<module>' moduleYour plan does not include the moduleCheck the key's modules, or upgrade the plan
internal error: ...The engine caught an unexpected failure on this inputThe app keeps running; report the file to support

Other messages describe the input: a malformed or truncated PDF, a page index out of range, invalid JSON options. They are meant to be logged as they are, not shown to users word for word.

License codes

NexPdfLicense.initialize (and NexPdfJni.licenseActivate) return 2 for a commercial key, 1 for a trial key, or one of:

CodeMeaning
-1Malformed key
-2Bad signature (the key was changed, or it is not a NexPDF key)
-3Unsupported key version (update the SDK)
-4Expired
-5Not yet valid (check the device clock)
-6Wrong platform (the key is not for android)
-7Wrong application id (the package name)
-8No key in the manifest or the assets (initialize(context) only)

A rejected key leaves the previous license state as it was, so an app that had no key stays in view-only mode, and an app that had a valid key keeps it.

invoke errors

NexPdfJni.invoke never throws either. It returns {"ok":false,"error":"..."} with the same messages; the NexPdfInvoke.call helper turns that into an IllegalStateException.

Untrusted input

The engine is written in Rust and fuzzed; a malformed PDF produces a failure value or an IllegalArgumentException, it does not crash the app. When you open files from other apps, a content: URI or a server:

  • check every return value, and catch IllegalArgumentException per file, so one bad file does not stop a batch;
  • check the file size before opening it, since the whole file is read into memory;
  • open and process files off the main thread (see Platform notes);
  • close documents with use { } or try-with-resources so native memory is freed on failure too.
fun pageCountOrNull(bytes: ByteArray): Int? = try {
    NexPdfDocument.openBytes(bytes).use { it.pageCount() }
} catch (e: IllegalArgumentException) {
    null
}

On this page