PDF assertions
On this page
PrestaFlow\Library\Support\Pdf is a thin wrapper around
smalot/pdfparser for asserting on the
text extracted from a PDF — invoices, credit notes, delivery slips,
e-tickets, gift cards.
The parser is instantiated lazily on the first read, and results are cached
per instance, so text(), pages(), contains() and matches() can be
chained without re-parsing.
#Load a PDF
Two entry points — from a file path, or from a raw binary string (useful when you fetched the PDF through an HTTP call or extracted it from an email attachment):
1use PrestaFlow\Library\Support\Pdf;2 3$pdf = Pdf::fromFile('/tmp/facture.pdf');4// or:5$pdf = Pdf::fromString($responseBody);
fromFile() throws RuntimeException if the path is missing or unreadable.
fromString() throws on an empty string.
#Read the content
| Method | Returns |
|---|---|
text(): string |
All pages concatenated with \n\n between them. |
pages(): string[] |
One entry per page, in order. |
pageCount(): int |
Number of pages. |
1$pdf->pageCount(); // 22$pdf->pages()[0]; // text of the first page3str_contains($pdf->text(), 'Facture');
#Assert on the content
#contains($needle, $caseSensitive = false)
Returns true if $needle appears in the concatenated text.
Case-insensitive by default: PDF text extraction preserves the source
casing (often uppercase for legal notices) and the assertion is meant to
read like a human-written check.
1$pdf->contains('TVA'); // true — matches "TVA" or "tva"2$pdf->contains('TVA', caseSensitive: true); // strict match
#matches($regex, $group = 0)
Runs preg_match_all on the concatenated text and returns the requested
capture group. Empty array on no match. Invalid regex raises
RuntimeException.
1$numbers = $pdf->matches('/Facture\s*#?\s*(\d+)/', 1);2// ['2024-000042']
#Use in a scenario
1use PrestaFlow\Library\Expects\Expect; 2use PrestaFlow\Library\Support\Pdf; 3 4$testSuite->it('the invoice PDF contains the order reference', function () use ($invoicePath, $orderReference) { 5 $pdf = Pdf::fromFile($invoicePath); 6 7 Expect::that($pdf->contains($orderReference))->isTheSameAs(true); 8 Expect::that($pdf->contains('TVA'))->isTheSameAs(true); 9 Expect::that($pdf->pageCount())->isGreaterThanOrEqualTo(1);10 11 $invoiceNumbers = $pdf->matches('/Facture\s*#?\s*(\d+)/', 1);12 Expect::that($invoiceNumbers)->isNotEmpty();13});
#Dependency
smalot/pdfparser ^2.11 is a runtime dependency of the library since 1.6.0
— nothing to add on the consumer side, composer update pulls it in.