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 Node.js.
License module
Structured extraction needs the conversion module (Startup tier and above).
Everything on this page runs offline, in-process, 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 calls are
on doc.raw and 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.
import { PdfDocument } from '@nexdevit/nexpdf-node';
const doc = await PdfDocument.open('statement.pdf');
for (const t of JSON.parse(doc.raw.extractTablesJson(-1)).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
doc.raw.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. 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));
const answer = await myLlm({ system: p.system, prompt: p.prompt, jsonSchema: p.response_schema }); // your call, returns text
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.
Extraction reads every page and blocks the event loop while it runs; in a server, run it in a worker thread.