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 Flutter.
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 results come back as decoded JSON (Map<String, Object?>), and failures throw
NexPdfException.
Tables
doc.extractTables(pageIndex: ..., options: ...) finds ruled tables (from the page's lines and
rectangles, with merged cells) and unruled tables (from column-aligned words). Leave pageIndex
out for every page.
import 'dart:io';
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
final doc = sdk.open(await File(statementPath).readAsBytes());
final tables = (doc.extractTables()['tables'] as List).cast<Map<String, Object?>>();
for (final t in tables) {
print('${t['page']} ${t['kind']} ${t['n_rows']} x ${t['n_cols']}');
print(t['markdown']);
final rows = [
for (final row in (t['rows'] as List).cast<List>())
[for (final cell in row.cast<Map<String, Object?>>()) 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.extractKeyValues(options: ...) 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.
final kv = doc.extractKeyValues(options: {'date_order': 'dmy'});
for (final p in (kv['pairs'] as List).cast<Map<String, Object?>>()) {
print('${p['key']} = ${p['value']} ${p['type']} ${p['normalized']}');
}
for (final e in (kv['entities'] as List).cast<Map<String, Object?>>()) {
print('${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.extractionPrompt(schema, options: ...)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.validateExtraction(schema, answer)checks and coerces the answer against the schema and finds each value on the pages.
final schema = {
'invoice_number': 'string',
'date': 'date',
'total': 'number',
'items': [
{'description': 'string', 'amount': 'number'},
],
};
final p = doc.extractionPrompt(schema);
final answer = await myLlm(p['system'], p['prompt'], p['response_schema']); // your call, returns text
final result = doc.validateExtraction(schema, answer);
if (result['valid'] == true) print((result['value'] as Map)['total']);
for (final f in (result['fields'] as List).cast<Map<String, Object?>>()) {
print('${f['path']} ${f['value']} ${f['found'] == true ? 'found on page ${f['page']}' : 'not found'}');
}
for (final e in (result['errors'] as List).cast<Map<String, Object?>>()) {
print('${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). sdk.validateExtraction(schema, answer) checks an answer
without a document, so nothing is found on pages.
Classification
doc.classify(labels) picks one of your labels from keywords. Known labels such as invoice and
contract have built-in keywords; others take keywords and a description.
final c = doc.classify([
'invoice',
'contract',
{'label': 'payslip', 'keywords': ['gross pay', 'net pay']},
]);
print(c['label']); // null when nothing matched
for (final s in (c['scores'] as List).cast<Map<String, Object?>>()) {
print('${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.