Skip to Content
NexPDF

Structured extraction

Let users extract fields to JSON in an Electron window, and extract tables, label/value pairs and typed entities, build prompts for your own language model, validate the answer and classify documents in the main process with NexPDF.

English

License module

Structured extraction needs the conversion module (Startup tier and above), in the window and in the document API.

Everything on this page except the window's model call runs offline and gives the same result every time. For schema extraction and classification, NexPDF builds the prompt and checks the answer; the engine's extraction calls never call a network service, so in code you choose and call the language model yourself.

In the window: Extract to JSON

Extract to JSON in the Convert mode (ai, 1.1 and later) takes a schema, a JSON Schema or the shorthand {"invoice_number":"string","date":"date","total":"number"}, and shows the extracted values as JSON with the page each one was found on. When the answer does not match the schema it lists the errors.

The window sends the prompt to the model through the engine's ANTHROPIC_API_KEY, as the assistant does (see Text and the assistant). Without the key it shows the label/value pairs found offline.

startEngine({ license, env: { ANTHROPIC_API_KEY } });    // or set process.env before openPdfWindow

The calls below run in the main process through the document API, on doc.raw. They return JSON strings.

Tables

doc.raw.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.

const { openDocumentFile } = require('@nexdevit/nexpdf-electron');

const doc = await openDocumentFile('statement.pdf');
for (const t of JSON.parse(doc.raw.extractTablesJson(-1, null)).tables) {
  console.log(t.page, t.kind, t.n_rows, 'x', t.n_cols);
  console.log(t.markdown);
  const rows = t.rows.map((row) => row.map((cell) => cell.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

doc.raw.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.

const kv = JSON.parse(doc.raw.extractKeyValuesJson('{"date_order":"dmy"}'));
for (const p of kv.pairs) console.log(p.key, '=', p.value, p.type, p.normalized);
for (const e of kv.entities) console.log(e.type, e.text, e.normalized);

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

Schema extraction with your language model

  1. doc.raw.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. doc.raw.extractionValidateJson(schemaJson, answer) checks and coerces the answer against the schema and finds each value on the pages.
const schema = JSON.stringify({
  invoice_number: 'string', date: 'date', total: 'number',
  items: [{ description: 'string', amount: 'number' }],
});

const p = JSON.parse(doc.raw.extractionPromptJson(schema, null));
const answer = await myLlm({ system: p.system, prompt: p.prompt, jsonSchema: p.response_schema });  // your call

const result = JSON.parse(doc.raw.extractionValidateJson(schema, answer));
if (result.valid) console.log(result.value.total);
for (const f of result.fields) console.log(f.path, f.value, f.found ? 'found on page' : 'not found', f.page);
for (const e of result.errors) console.log(e.path, e.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).

Classification

doc.raw.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.

const c = JSON.parse(doc.raw.classifyDocumentJson(JSON.stringify(
  ['invoice', 'contract', { label: 'payslip', keywords: ['gross pay', 'net pay'] }])));
console.log(c.label);                  // null when nothing matched
for (const s of c.scores) console.log(s.label, s.score, s.confidence, s.matched);

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

On this page