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

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.

type Table struct {
	Page     int    `json:"page"`
	Kind     string `json:"kind"`
	NRows    int    `json:"n_rows"`
	NCols    int    `json:"n_cols"`
	CSV      string `json:"csv"`
	Markdown string `json:"markdown"`
	Rows     [][]struct {
		Text string `json:"text"`
	} `json:"rows"`
}

doc, err := nexpdf.Open("statement.pdf")
if err != nil {
	log.Fatal(err)
}
defer doc.Close()

s, err := doc.ExtractTablesJSON(-1, "")
if err != nil {
	log.Fatal(err)
}
var result struct {
	Tables []Table `json:"tables"`
}
json.Unmarshal([]byte(s), &result)
for _, t := range result.Tables {
	fmt.Println(t.Page, t.Kind, t.NRows, "x", t.NCols)
	fmt.Println(t.Markdown)
}

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.

s, err := doc.ExtractKeyValuesJSON(`{"date_order":"dmy"}`)
if err != nil {
	log.Fatal(err)
}
var kv struct {
	Pairs []struct {
		Key        string `json:"key"`
		Value      string `json:"value"`
		Type       string `json:"type"`
		Normalized any    `json:"normalized"`
	} `json:"pairs"`
	Entities []struct {
		Type       string `json:"type"`
		Text       string `json:"text"`
		Normalized any    `json:"normalized"`
	} `json:"entities"`
}
json.Unmarshal([]byte(s), &kv)
for _, p := range kv.Pairs {
	fmt.Println(p.Key, "=", p.Value, p.Type, p.Normalized)
}
for _, e := range kv.Entities {
	fmt.Println(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.
schema := `{"invoice_number":"string","date":"date","total":"number",
	"items":[{"description":"string","amount":"number"}]}`

s, err := doc.ExtractionPromptJSON(schema, "")
if err != nil {
	log.Fatal(err)
}
var p struct {
	System         string          `json:"system"`
	Prompt         string          `json:"prompt"`
	ResponseSchema json.RawMessage `json:"response_schema"`
}
json.Unmarshal([]byte(s), &p)

answer := myLLM(p.System, p.Prompt, p.ResponseSchema) // your call, returns the model's text

s, err = doc.ExtractionValidateJSON(schema, answer)
if err != nil {
	log.Fatal(err)
}
var result struct {
	Valid  bool           `json:"valid"`
	Value  map[string]any `json:"value"`
	Fields []struct {
		Path  string `json:"path"`
		Value any    `json:"value"`
		Found bool   `json:"found"`
		Page  *int   `json:"page"`
	} `json:"fields"`
	Errors []struct {
		Path    string `json:"path"`
		Message string `json:"message"`
	} `json:"errors"`
}
json.Unmarshal([]byte(s), &result)
if result.Valid {
	fmt.Println(result.Value["total"])
}
for _, f := range result.Fields {
	fmt.Println(f.Path, f.Value, f.Found, f.Page)
}
for _, e := range result.Errors {
	fmt.Println(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.

s, err := doc.ClassifyDocumentJSON(
	`["invoice","contract",{"label":"payslip","keywords":["gross pay","net pay"]}]`)
if err != nil {
	log.Fatal(err)
}
var c struct {
	Label  *string `json:"label"` // nil when nothing matched
	Scores []struct {
		Label      string   `json:"label"`
		Score      float64  `json:"score"`
		Confidence float64  `json:"confidence"`
		Matched    []string `json:"matched"`
	} `json:"scores"`
}
json.Unmarshal([]byte(s), &c)
if c.Label != nil {
	fmt.Println(*c.Label)
}

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

On this page