Structured extraction
Extract tables, label/value pairs and typed entities, build prompts for schema extraction with your own language model, validate the answer and classify documents with NexPDF for Android.
License module
Structured extraction needs the conversion module (Startup tier and above).
Everything on this page runs offline and gives the same result every time. For schema extraction and classification, NexPDF builds the prompt and checks the answer; the engine never calls a network service, so you choose and call the language model yourself.
Each call returns JSON text, or an empty string on failure with the reason in
NexPdfJni.lastError(). The NexPdfDocument methods below are also NexPdfJni methods that take
doc.handle() first.
Tables
extractTablesJson(pageIndex, optionsJson) finds ruled tables (from the page's lines and
rectangles, with merged cells) and unruled tables (from column-aligned words). Pass -1 for every
page.
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONObject
NexPdfDocument.openBytes(statement).use { doc ->
val tables = JSONObject(doc.extractTablesJson(-1, null)).getJSONArray("tables")
for (i in 0 until tables.length()) {
val t = tables.getJSONObject(i)
Log.i("NexPDF", "${t.getInt("page")} ${t.getString("kind")} ${t.getInt("n_rows")} x ${t.getInt("n_cols")}")
Log.i("NexPDF", t.getString("markdown"))
val firstRow = t.getJSONArray("rows").getJSONArray(0)
val firstCell = firstRow.getJSONObject(0).getString("text")
}
}Each table has page, bbox, kind (ruled or unruled), n_rows, n_cols, header_rows,
rows (cells with text, bbox, row, col, row_span, col_span), and the table as csv
and markdown. Options: {"ruled":true,"unruled":true,"min_unruled_lines":3}.
Key-value pairs and entities
extractKeyValuesJson(optionsJson) reads label/value pairs from the layout (Invoice no.: 123, a
label above its value, labelled cells) and typed entities: dates, amounts with currency, IBANs,
e-mail addresses, phone numbers and VAT numbers, with normalised values.
val kv = JSONObject(doc.extractKeyValuesJson("""{"date_order":"dmy"}"""))
val pairs = kv.getJSONArray("pairs")
for (i in 0 until pairs.length()) {
val p = pairs.getJSONObject(i)
Log.i("NexPDF", "${p.getString("key")} = ${p.opt("value")} ${p.getString("type")} ${p.opt("normalized")}")
}
val entities = kv.getJSONArray("entities")
for (i in 0 until entities.length()) {
val e = entities.getJSONObject(i)
Log.i("NexPDF", "${e.getString("type")} ${e.getString("text")} ${e.opt("normalized")}")
}Options: pages (0-based indices) and date_order (dmy or mdy) for ambiguous dates.
Schema extraction with your language model
extractionPromptJson(schemaJson, optionsJson)builds a prompt from the page text in reading order, the tables as Markdown and the detected key-values.- Send
systemandpromptto the model of your choice. extractionValidateJson(schemaJson, answer)checks and coerces the answer against the schema and finds each value on the pages.
val schema = """{"invoice_number":"string","date":"date","total":"number",
"items":[{"description":"string","amount":"number"}]}"""
val p = JSONObject(doc.extractionPromptJson(schema, null))
val answer = myLlm(p.getString("system"), p.getString("prompt"), p.getJSONObject("response_schema")) // your call
val result = JSONObject(doc.extractionValidateJson(schema, answer))
if (result.getBoolean("valid")) {
Log.i("NexPDF", "total ${result.getJSONObject("value").opt("total")}")
}
val fields = result.getJSONArray("fields")
for (i in 0 until fields.length()) {
val f = fields.getJSONObject(i)
Log.i("NexPDF", "${f.getString("path")} ${f.opt("value")} ${if (f.getBoolean("found")) "found on page ${f.opt("page")}" else "not found"}")
}
val errors = result.getJSONArray("errors")
for (i in 0 until errors.length()) {
val e = errors.getJSONObject(i)
Log.w("NexPDF", "${e.getString("path")}: ${e.getString("message")}")
}The schema is a JSON Schema or the shorthand above ("string", "number", "date", arrays of
objects). The prompt result also has pages, chars and truncated. Prompt options:
max_chars (default 60000), pages, tables, key_values and instructions.
The answer may be plain JSON, fenced JSON or JSON inside prose. The report has valid, the coerced
value, errors and warnings, and fields with path, value, found, page, bbox and
match (exact or normalized). To validate an answer without a document, call
NexPdfJni.extractionValidateJson(0, schemaJson, answer): handle 0 skips the grounding on pages.
Classification
classifyJson(labelsJson) (NexPdfJni.classifyDocumentJson(handle, labelsJson)) picks one of your
labels from keywords. Known labels such as invoice and contract have built-in keywords; others
take keywords and a description.
val c = JSONObject(doc.classifyJson(
"""["invoice","contract",{"label":"payslip","keywords":["gross pay","net pay"]}]"""))
Log.i("NexPDF", "label: ${if (c.isNull("label")) "none" else c.getString("label")}") // null when nothing matched
val scores = c.getJSONArray("scores")
for (i in 0 until scores.length()) {
val s = scores.getJSONObject(i)
Log.i("NexPDF", "${s.getString("label")} ${s.getDouble("score")} ${s.getDouble("confidence")} ${s.get("matched")}")
}The result also holds system, prompt and response_schema, ready for a language model when you
want it to decide.