Laravel PDF testing

How to test page breaks and footers in a Laravel Snappy invoice

Print a two-page Blade invoice on both servers. Use pdfinfo and pdftotext to catch misplaced totals, missing line items, and wrong page numbers.

Marqius

Printed proofs with trim marks on an ivory proofing table

The invoice download still returns a PDF after a server upgrade. The order number is right and the total is right. But if the total has slipped onto the packing page, a warehouse clerk may hand the customer a sheet without the amount due. A test that searches the whole PDF for “120.00” will still pass.

Here is a small Laravel Snappy regression test you can run on the current server and on its replacement. It checks that each line appears exactly once on the expected page and that both footers are numbered correctly. The fixture uses invented order data and runs from the command line inside your existing app.

You can copy each file below or download the Blade view, both scripts, and a passing invoice (ZIP).

1. Set up an invoice with two predictable pages

Use a staging copy or a disposable local checkout of a Laravel app that already generates PDFs with barryvdh/laravel-snappy. You will need PHP, your working wkhtmltopdf executable, and Poppler’s pdfinfo and pdftotext commands. The checker runs in a Unix shell on Linux or macOS and uses awk, diff, and mktemp. For this example, the wkhtmltopdf build must support printed footers. Laravel Snappy package documentation · How pdftotext selects pages

From the app root, create the folders for one Blade view and two small scripts. None of them needs a public route.

Terminal
mkdir -p resources/views/pdf-check tools/pdf-check
command -v wkhtmltopdf
pdfinfo -v
pdftotext -v

If the first command after mkdir prints no path, use the full binary path from your app’s Snappy configuration in step 2. Save this as resources/views/pdf-check/invoice.blade.php. The packing lines belong on page one. A deliberate CSS break starts the payment summary on page two.

html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Invoice {{ $number }}</title>
    <style>
        body { font: 14px sans-serif; color: #17252f; }
        h1 { font-size: 25px; }
        table { width: 100%; border-collapse: collapse; }
        td, th { padding: 8px 0; border-bottom: 1px solid #ccc; text-align: left; }
        .amount { text-align: right; }
        .summary { page-break-before: always; }
    </style>
</head>
<body>
    <h1>Invoice {{ $number }}</h1>
    <table>
        <tr><th>Description</th><th class="amount">Amount</th></tr>
        @foreach ($items as $item)
            <tr><td>{{ $item['name'] }}</td><td class="amount">{{ number_format($item['cents'] / 100, 2) }} EUR</td></tr>
        @endforeach
    </table>
    <div class="summary">
        <h1>Payment summary</h1>
        <table>
            <tr><td>Subtotal</td><td class="amount">{{ number_format($subtotal / 100, 2) }} EUR</td></tr>
            <tr><td>VAT</td><td class="amount">{{ number_format($vat / 100, 2) }} EUR</td></tr>
            <tr><td>Total due</td><td class="amount">{{ number_format(($subtotal + $vat) / 100, 2) }} EUR</td></tr>
        </table>
    </div>
</body>
</html>

2. Print through the same Laravel service your app uses

Save this as tools/pdf-check/render.php. It boots your application, renders the Blade view with Snappy, and saves the PDF under storage/app/pdf-check/. Supplying the executable path makes it possible to repeat the run with the precise binary used by a queue worker.

php
<?php
declare(strict_types=1);

use Illuminate\Contracts\Console\Kernel;

$root = dirname(__DIR__, 2);
require $root . '/vendor/autoload.php';
$app = require $root . '/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();

$binary = realpath($argv[1] ?? '');
if ($binary === false || !is_file($binary) || !is_executable($binary)) {
    fwrite(STDERR, "Pass the path to an executable wkhtmltopdf binary.\n");
    exit(1);
}
config(['snappy.pdf.binary' => $binary]);

$items = [
    ['name' => 'Design services', 'cents' => 3600],
    ['name' => 'Print preparation', 'cents' => 6400],
];
$subtotal = array_sum(array_column($items, 'cents'));
$vat = intdiv($subtotal * 20, 100);
$directory = storage_path('app/pdf-check');
if (!is_dir($directory)) {
    mkdir($directory, 0755, true);
}

app('snappy.pdf.wrapper')
    ->loadView('pdf-check.invoice', ['number' => 'INV-1001', 'items' => $items, 'subtotal' => $subtotal, 'vat' => $vat])
    ->setPaper('a4')
    ->setOption('margin-bottom', 18)
    ->setOption('footer-center', 'Page [page] from [toPage]')
    ->setOption('footer-font-size', 9)
    ->save($directory . '/invoice.pdf', true);

echo $directory . "/invoice.pdf\n";

Run it from the app root. Substitute the full path from your Snappy configuration if the executable is outside your shell’s search path.

Terminal
php tools/pdf-check/render.php "$(command -v wkhtmltopdf)"
pdfinfo storage/app/pdf-check/invoice.pdf

Look for Pages: 2 in the output. The page count is the first check. It cannot tell you which page the total landed on. pdfinfo documentation

3. Check each page on its own

Save this as tools/pdf-check/check.sh. It extracts each page separately, removes blank lines, and collapses runs of spaces. It then compares every remaining line in order. A missing footer, a duplicated total, or a total on the packing page should make the script exit with an error.

Terminal
#!/bin/sh
set -eu
export LC_ALL=C
pdf=${1:?Pass the path to the invoice PDF}
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

pages=$(pdfinfo "$pdf" | awk '/^Pages:/ {print $2}')
if [ "$pages" != 2 ]; then
    echo "FAIL: expected 2 pages, found $pages" >&2
    exit 1
fi
cat > "$tmp/expected-1" <<'PAGE1'
Invoice INV-1001
Description Amount
Design services 36.00 EUR
Print preparation 64.00 EUR
Page 1 from 2
PAGE1
cat > "$tmp/expected-2" <<'PAGE2'
Payment summary
Subtotal 100.00 EUR
VAT 20.00 EUR
Total due 120.00 EUR
Page 2 from 2
PAGE2

for page in 1 2; do
    pdftotext -f "$page" -l "$page" -layout -nopgbrk "$pdf" "$tmp/raw"
    awk 'NF {$1=$1; print}' "$tmp/raw" > "$tmp/actual-$page"
    if ! diff -u "$tmp/expected-$page" "$tmp/actual-$page"; then
        echo "FAIL: page $page has different text or line order" >&2
        exit 1
    fi
done
echo 'PASS: two pages, both line items, 120.00 EUR total on page 2, and both footers'
Terminal
sh tools/pdf-check/check.sh storage/app/pdf-check/invoice.pdf

The unchanged fixture produces this result.

text
PASS: two pages, both line items, 120.00 EUR total on page 2, and both footers

We ran this on macOS with Laravel 12.73.0, Laravel Snappy 1.0.5, and upstream wkhtmltopdf 0.12.6 with patched Qt. The checker rejected eight deliberately broken PDFs, including a total moved to page one, a duplicated total, a wrong amount, and an incorrect second footer.

To see a failure for yourself, temporarily remove the CSS rule that starts the summary on a new page. Render again and run the checker. With this short example the summary fits on page one, so the page-count check fails. Restore the rule and rerun before saving your reference PDF.

4. Compare the old server with the new one

Keep the passing PDF from the old server as before.pdf. Run the same view and scripts on the new server, with the fonts, paper size, executable, and Snappy settings used there. Save its output as after.pdf. Record the versions with each file so you can trace any change.

Terminal
php -v
composer show barryvdh/laravel-snappy
wkhtmltopdf --version
pdftotext -v

If the renderer lives outside your shell’s search path, run the same executable you passed to the PHP script with --version. View both PDFs side by side at the same zoom. On page two, compare the position of the total against the right margin. Page assertions can pass even if a fallback font widens that number or pushes it across a preprinted box.

For a closer look, export each word’s bounding box. Find the 120.00 amount in the payment summary and compare its horizontal position. The left edge is xMin, measured in PDF points. A difference of 72 points equals one inch.

Terminal
pdftotext -f 2 -l 2 -bbox before.pdf before-page-2.html
pdftotext -f 2 -l 2 -bbox after.pdf after-page-2.html

Once this small check passes, try the longest real invoice layout you support with synthetic data. Use a long billing address, a description that wraps to three lines, or enough items to span a natural page break. These cases exercise the places where a server’s fonts and spacing can change what the customer receives.

Reader questions

Why use a forced page break if my invoices flow naturally?

The forced break gives the check a predictable boundary. It catches a missing CSS rule or a footer that drifted to the wrong page. A second fixture with a naturally overflowing table tests how many rows your actual invoice can fit.

Why would the footer disappear when the page count stays the same?

Some wkhtmltopdf builds lack support for footer options and print a warning when they ignore them. Check the renderer’s stderr and the executable used by your queue worker. A valid two-page PDF can still have two blank footers.

Can a successful text check prove two PDFs look the same?

It establishes that the chosen words appeared on their expected pages. To review placement, compare both PDFs at the same zoom or compare word coordinates for fields such as the total, payment reference, and footer.