Skip to Content
NexPDF

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 Java.

English

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.

The examples read the JSON results with Jackson; any JSON library works.

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.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexdevit.nexpdf.NexPdfDocument;
import java.nio.file.Path;

ObjectMapper json = new ObjectMapper();
try (NexPdfDocument doc = NexPdfDocument.open(Path.of("statement.pdf"))) {
    for (JsonNode t : json.readTree(doc.extractTablesJson(-1, null)).get("tables")) {
        System.out.println(t.get("page") + " " + t.get("kind").asText() + " "
                + t.get("n_rows") + " x " + t.get("n_cols"));
        System.out.println(t.get("markdown").asText());
        for (JsonNode row : t.get("rows")) {
            for (JsonNode cell : row) System.out.print(cell.get("text").asText() + "\t");
            System.out.println();
        }
    }
}

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.

JsonNode kv = json.readTree(doc.extractKeyValuesJson("{\"date_order\":\"dmy\"}"));
for (JsonNode p : kv.get("pairs")) {
    System.out.println(p.get("key").asText() + " = " + p.get("value").asText() + " "
            + p.get("type") + " " + p.get("normalized"));
}
for (JsonNode e : kv.get("entities")) {
    System.out.println(e.get("type").asText() + " " + e.get("text").asText() + " " + e.get("normalized"));
}

Options: pages (0-based indices) and date_order (dmy or mdy) for ambiguous dates.

Schema extraction with your language model

  1. extractionPromptJson(schemaJson, optionsJson) builds a prompt from the page text in reading order, the tables as Markdown and the detected key-values.
  2. Send system and prompt to the model of your choice.
  3. extractionValidateJson(schemaJson, answer) checks and coerces the answer against the schema and finds each value on the pages.
String schema = """
    {"invoice_number":"string","date":"date","total":"number",
     "items":[{"description":"string","amount":"number"}]}
    """;

JsonNode p = json.readTree(doc.extractionPromptJson(schema, null));
String answer = myLlm.complete(p.get("system").asText(), p.get("prompt").asText(),
        p.get("response_schema").toString());                      // your call

JsonNode result = json.readTree(doc.extractionValidateJson(schema, answer));
if (result.get("valid").asBoolean()) {
    System.out.println(result.get("value").get("total"));
}
for (JsonNode f : result.get("fields")) {
    System.out.println(f.get("path").asText() + " " + f.get("value") + " "
            + (f.get("found").asBoolean() ? "found on page " + f.path("page") : "not found"));
}
for (JsonNode e : result.get("errors")) {
    System.out.println(e.get("path").asText() + " " + e.get("message").asText());
}

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).

Classification

classifyDocumentJson(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.

JsonNode c = json.readTree(doc.classifyDocumentJson("""
    ["invoice","contract",{"label":"payslip","keywords":["gross pay","net pay"]}]
    """));
System.out.println(c.get("label"));            // null when nothing matched
for (JsonNode s : c.get("scores")) {
    System.out.println(s.get("label").asText() + " " + s.get("score") + " "
            + s.get("confidence") + " " + s.get("matched"));
}

The result also holds system, prompt and response_schema, ready for a language model when you want it to decide.

On this page