Skip to Content
NexPDF

Text extraction

Extract page text, Markdown and positioned text blocks with NexPDF for .NET, and retrieve passages for a language model.

English

License module

Text extraction, Markdown export and the offline assistant are part of the viewer module and work without a key.

Plain text of a page

ExtractPageText(pageIndex) returns the text of a page in reading order, with the layout reconstructed into lines and paragraphs:

using Nexdevit.NexPdf;

using var doc = NexPdfDocument.Open("contract.pdf");
var text = string.Join("\n\n", Enumerable.Range(0, doc.PageCount).Select(doc.ExtractPageText));

The whole document as Markdown

ExtractMarkdown() (or its alias ToMarkdown()) keeps headings, lists and tables, which makes it a good input for search indexes and language models:

var markdown = doc.ExtractMarkdown();

Text blocks with positions

PageBlocksJson(pageIndex) returns the text blocks of a page with their font size and rectangle in PDF points:

using System.Text.Json.Nodes;

foreach (var block in JsonNode.Parse(doc.PageBlocksJson(0))!.AsArray())
{
    var t = block!["text"]!.GetValue<string>();
    Console.WriteLine($"{block["size"]!.GetValue<double>(),5:F1}pt  {t[..Math.Min(60, t.Length)]}");
}

Each block has text, size, llx, lly, urx and ury.

Words with exact boxes

PageWordsJson(pageIndex, optionsJson) returns the words of a page with boxes computed from the fonts' glyph widths:

var words = JsonNode.Parse(doc.PageWordsJson(0))!;
foreach (var w in words["words"]!.AsArray())
    Console.WriteLine($"{w!["text"]} {w["bbox"]!.ToJsonString()} line {w["line"]}");

Each word has text, bbox ([llx, lly, urx, ury]), quad (eight numbers: baseline start, baseline end, top end, top start, so it follows rotated text), font, size, angle and line. {"glyphs":true} adds a glyphs list (text, bbox, quad, code) to each word.

Extracted text is in logical order: right-to-left and shaped text written by NexPDF copies and extracts as typed.

Passages for a language model

AskDocumentJson(question, k, maxChars) ranks the passages of the document against a question, offline, and returns the k best (default 5) with a page-tagged context you can send to a language model. maxChars = 0 uses the default limit (200,000 characters).

var result = JsonNode.Parse(doc.AskDocumentJson("When does the contract end?", 5))!;
foreach (var p in result["passages"]!.AsArray())
    Console.WriteLine($"{p!["page"]} {p["score"]!.GetValue<double>():F2}");

var prompt = $"Answer from this document:\n{result["context"]}\n\nQuestion: When does the contract end?";

Scanned documents

Pages that are images have no text to extract. Run OCR first to add a searchable text layer.

On this page