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

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.

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.

using System.Text.Json.Nodes;
using Nexdevit.NexPdf;

using var doc = NexPdfDocument.Open("statement.pdf");
foreach (var t in JsonNode.Parse(doc.ExtractTablesJson(-1))!["tables"]!.AsArray())
{
    Console.WriteLine($"{t!["page"]} {t["kind"]} {t["n_rows"]} x {t["n_cols"]}");
    Console.WriteLine(t["markdown"]);
    var rows = t["rows"]!.AsArray()
        .Select(row => row!.AsArray().Select(cell => cell!["text"]!.GetValue<string>()).ToList())
        .ToList();
}

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.

var kv = JsonNode.Parse(doc.ExtractKeyValuesJson("""{"date_order":"dmy"}"""))!;
foreach (var p in kv["pairs"]!.AsArray())
    Console.WriteLine($"{p!["key"]} = {p["value"]} {p["type"]} {p["normalized"]}");
foreach (var e in kv["entities"]!.AsArray())
    Console.WriteLine($"{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. 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.
var schema = """
    {"invoice_number":"string","date":"date","total":"number",
     "items":[{"description":"string","amount":"number"}]}
    """;

var p = JsonNode.Parse(doc.ExtractionPromptJson(schema))!;
var answer = await myLlm.CompleteAsync((string)p["system"]!, (string)p["prompt"]!,
    p["response_schema"]!.ToJsonString());                     // your call

var result = JsonNode.Parse(doc.ExtractionValidateJson(schema, answer))!;
if (result["valid"]!.GetValue<bool>())
    Console.WriteLine(result["value"]!["total"]);
foreach (var f in result["fields"]!.AsArray())
    Console.WriteLine($"{f!["path"]} {f["value"]} {(f["found"]!.GetValue<bool>() ? $"found on page {f["page"]}" : "not found")}");
foreach (var e in result["errors"]!.AsArray())
    Console.WriteLine($"{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

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.

var c = JsonNode.Parse(doc.ClassifyDocumentJson("""
    ["invoice","contract",{"label":"payslip","keywords":["gross pay","net pay"]}]
    """))!;
Console.WriteLine(c["label"]);                 // null when nothing matched
foreach (var s in c["scores"]!.AsArray())
    Console.WriteLine($"{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