Skip to Content
NexPDF

Text extraction

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

use Nexdevit\NexPdf\Document;

$doc = Document::open('contract.pdf');
$pages = [];
for ($i = 0; $i < $doc->pageCount(); $i++) {
    $pages[] = $doc->extractPageText($i);
}
$text = implode("\n\n", $pages);

The whole document as Markdown

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

$markdown = $doc->extractMarkdown();

Text blocks with positions

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

foreach (json_decode($doc->pageBlocksJson(0), true) as $block) {
    printf("%5.1fpt  %s\n", $block['size'], mb_substr($block['text'], 0, 60));
}

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 and the text state:

$page = json_decode($doc->pageWordsJson(0), true);
foreach ($page['words'] as $w) {
    printf("%s [%s] %s %.1f\n", $w['text'], implode(', ', $w['bbox']), $w['font'], $w['size']);
}

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

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).

$result = json_decode($doc->askDocument('When does the contract end?', 5, 0), true);
foreach ($result['passages'] as $p) {
    echo $p['page'], ' ', round($p['score'], 2), ' ', mb_substr($p['text'], 0, 80), "\n";
}

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