Skip to Content
NexPDF

Text extraction

Extract page text, Markdown and positioned text blocks with NexPDF for Android, 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

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

import com.nexdevit.nexpdf.NexPdfDocument

val text = NexPdfDocument.openBytes(bytes).use { doc ->
    (0 until doc.pageCount()).joinToString("\n\n") { doc.pageText(it) }
}

The whole document as Markdown

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

val markdown = doc.toMarkdown()

Text blocks with positions

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

val blocks = JSONArray(NexPdfJni.pageBlocksJson(doc.handle(), 0))
for (i in 0 until blocks.length()) {
    val b = blocks.getJSONObject(i)
    Log.i("NexPDF", "%5.1fpt  %s".format(b.getDouble("size"), b.getString("text").take(60)))
}

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

Passages for a language model

NexPdfJni.askDocument(handle, 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).

val result = JSONObject(NexPdfJni.askDocument(doc.handle(), "When does the contract end?", 5, 0))

val passages = result.getJSONArray("passages")
for (i in 0 until passages.length()) {
    val p = passages.getJSONObject(i)
    Log.i("NexPDF", "${p.getInt("page")} ${p.getDouble("score")} ${p.getString("text").take(80)}")
}
val prompt = "Answer from this document:\n${result.getString("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