Skip to Content
NexPDF

Text extraction

Extract page text, Markdown and positioned text blocks with NexPDF for iOS (Swift), 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:

import NexPdf

let doc = try NexPdfDocument.open(url: url)
let text = try (0..<doc.pages).map { try doc.extractPageText(pageIndex: $0) }.joined(separator: "\n\n")

The whole document as Markdown

extractMarkdown() keeps headings, lists and tables, which makes it a good input for search indexes and language models:

let markdown = try doc.extractMarkdown()

Text blocks with positions

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

let blocks = NexPdf.json(try doc.pageBlocksJson(pageIndex: 0)) as? [[String: Any]] ?? []
for block in blocks {
    print(block["size"] ?? 0, block["text"] ?? "")
}

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, for highlighting or redacting single words:

let page = NexPdf.json(try doc.pageWordsJson(pageIndex: 0, optionsJson: #"{"glyphs":false}"#)) as? [String: Any] ?? [:]
for w in page["words"] as? [[String: Any]] ?? [] {
    print(w["text"] ?? "", w["bbox"] ?? [], w["line"] ?? 0)
}

The result is {"page", "words": [...]}. 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. With {"glyphs": true} each word also has glyphs, one box per character (text, bbox, quad, code).

Passages for a language model

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

let result = NexPdf.json(try doc.askDocument(question: "When does the contract end?", k: 5, maxChars: 0)) as? [String: Any]
for p in result?["passages"] as? [[String: Any]] ?? [] {
    print(p["page"] ?? 0, p["score"] ?? 0, p["text"] ?? "")
}
let context = result?["context"] as? String ?? ""
let prompt = "Answer from this document:\n\(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