Skip to Content
NexPDF

Text extraction

Extract page text, Markdown and positioned text blocks in the browser with NexPDF for the web, 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

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

const doc = await nex.PdfDocument.fromFile(file);
const pages = Array.from({ length: doc.pageCount }, (_, i) => doc.text(i));
const text = pages.join('\n\n');

The whole document as Markdown

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

const markdown = doc.markdown();

Text blocks with positions

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

const blocks = JSON.parse(doc.raw.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

doc.raw.pageWordsJson(page, optionsJson) returns the words of a page with boxes computed from the fonts' glyph widths and the text state:

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

const withGlyphs = JSON.parse(doc.raw.pageWordsJson(0, '{"glyphs":true}'));

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 glyphs to each word, with text, bbox, quad and code.

Passages for a language model

doc.raw.askDocument(question, k, maxChars) ranks the passages of the document against a question, offline and in the page, 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(doc.raw.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