Skip to Content
NexPDF

Text extraction

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

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

import nexpdf

with nexpdf.Document.open("contract.pdf") as doc:
    text = "\n\n".join(doc.extract_page_text(i) for i in range(doc.page_count()))

The whole document as Markdown

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

markdown = doc.extract_markdown()

Text blocks with positions

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

for block in nexpdf.loads(doc.page_blocks_json(0)):
    print(f'{block["size"]:>5.1f}pt  {block["text"][:60]}')

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

Words with exact boxes

page_words_json(page_index, options_json) returns the words of a page with boxes computed from the fonts' glyph widths and the text state:

page = nexpdf.loads(doc.page_words_json(0))
for w in page["words"]:
    print(w["text"], w["bbox"], w["font"], w["size"], w["angle"], 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 per word with text, bbox, quad and code.

Vertical CJK text is read as columns from right to left.

Passages for a language model

ask_document(question, k, max_chars) 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. max_chars=0 uses the default limit (200,000 characters).

result = nexpdf.loads(doc.ask_document("When does the contract end?", 5, 0))
for p in result["passages"]:
    print(p["page"], round(p["score"], 2), p["text"][:80])

prompt = f"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