Skip to Content
NexPDF

Text extraction

Extract page text, Markdown and positioned text blocks on the device with NexPDF for React Native, 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(page) resolves to the text of a page in reading order, with the layout reconstructed into lines and paragraphs:

const doc = await NexPdf.open(base64Pdf);
const count = await doc.pageCount();
const pages = await Promise.all(Array.from({ length: count }, (_, i) => doc.extractPageText(i)));
const text = pages.join('\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:

const markdown = await doc.extractMarkdown();

Text blocks with positions

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

const blocks = JSON.parse(await doc.pageBlocksJson(0));
for (const b of blocks) console.log(b.size.toFixed(1), b.text.slice(0, 60));

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

Words with exact boxes

pageWordsJson(page, optionsJson) resolves to the words of a page with boxes computed from the fonts' glyph widths, for highlighting or redacting single words:

const { words } = JSON.parse(await doc.pageWordsJson(0, null));
for (const w of words) console.log(w.text, w.bbox, w.line);

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 on the device, 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).

const question = 'When does the contract end?';
const result = JSON.parse(await doc.askDocument(question, 5, 0));
for (const p of result.passages) console.log(p.page, p.score.toFixed(2), p.text.slice(0, 80));

const prompt = `Answer from this document:\n${result.context}\n\nQuestion: ${question}`;

Scanned documents

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

On this page