Skip to content

Novis\Pdf\Reader::text

$reader->text(uint $page): tainted string$reader->text(
    uint $page,
): tainted string

Returns the text of one page of a PDF file.

text takes a page number. Pages count from 1. The result is the text of that page, in the order the file stores it, with one line of the page on each line of the result. Tables and columns are not rebuilt, so the text of two columns can be mixed.

Reader::open reads the file once and keeps it until the request ends. Each call to text reads that copy. You can call text for many pages, and the file is not copied or read again.

A page number past the end of the file throws a LogicError. A page whose content unpacks to more than 64 MB, or to more than 1000 times its packed size, throws a ParseError. The server's [limits] set these two numbers, as for Reader::open.

The examples below print the text of each page, show the error for a page past the end, and find the line with the total on an invoice.

Parameters

  • $pageuint

Return value

Returns tainted string.

Examples

The text of each page

<?nvs
// Shows how to read the text of each page of a received PDF file.
use Novis\Pdf\Document;
use Novis\Pdf\Reader;
// The received file. Here the program renders it first, so the example has a file to read.
var $received = Document::fromHtml(
'<h1>Delivery note</h1><p>3 bikes</p>'
. "<h1 style=\"break-before: page\">Returns</h1><p>1 helmet</p>",
)->render()->bytes;
// Pages count from 1. Each line of text on the page is one line in the result.
var $reader = Reader::open($received);
for (uint $page = 1; $page <= $reader->pageCount; $page++) {
echo 'page ', $page, ': ', Core\Str::replace($reader->text($page), "\n", ' / '), "\n";
}
Output
page 1: Delivery note / 3 bikes
page 2: Returns / 1 helmet

A page past the end

<?nvs
// Shows the error for a page number that the file does not have.
use Novis\Pdf\Document;
use Novis\Pdf\Reader;
var $reader = Reader::open(Document::fromHtml('<p>Receipt 1042</p>')->render()->bytes);
// The receipt has one page, so page 2 throws a `LogicError`.
try {
echo $reader->text(2), "\n";
} catch (LogicError $error) {
echo 'LogicError: ', $error->message, "\n";
}
Output
LogicError: page 2 is outside the PDF, which has 1 page

Find the page with the total

<?nvs
// Shows how to find the page of a received invoice that has the total on it.
use Novis\Pdf\Document;
use Novis\Pdf\Reader;
var $invoice = Document::fromHtml(
'<style>p { break-after: page }</style>'
. '<p>Invoice 1042</p><p>Items: 3 bikes</p><p>Total: 1,250.00 EUR</p>',
)->render()->bytes;
// This loop checks each line of each page. It prints the line that starts with `Total`.
var $reader = Reader::open($invoice);
for (uint $page = 1; $page <= $reader->pageCount; $page++) {
foreach (Core\Str::lines($reader->text($page)) as tainted string $line) {
if (Core\Str::startsWith($line, 'Total')) {
echo 'page ', $page, ': ', $line, "\n";
}
}
}
Output
page 3: Total: 1,250.00 EUR