How to add page number for every page in laravel dompdf?

3 min read 07-10-2024
How to add page number for every page in laravel dompdf?


Adding Page Numbers to Every Page in Laravel with Dompdf

Generating PDFs in Laravel using Dompdf is a common task. However, sometimes you need to add page numbers to make your documents more user-friendly. This article will guide you through the process of adding page numbers to every page of your PDF documents generated with Dompdf.

Understanding the Challenge

Imagine you're generating a multi-page invoice in Laravel using Dompdf. You'd like to include page numbers on each page for easy reference. But the default Dompdf setup doesn't automatically add these numbers. This article will show you how to overcome this by incorporating page numbering directly into your PDF creation process.

The Setup

Let's start with a basic example. Here's a simple controller function that generates a PDF using Dompdf:

use App\Http\Controllers\Controller;
use Barryvdh\DomPDF\Facade as PDF;

class InvoiceController extends Controller
{
    public function generateInvoice()
    {
        $data = [
            'invoice_number' => 'INV-1234',
            'customer_name' => 'John Doe',
            'items' => [
                ['name' => 'Product A', 'quantity' => 2, 'price' => 100],
                ['name' => 'Product B', 'quantity' => 1, 'price' => 50],
            ],
        ];

        $pdf = PDF::loadView('invoices.invoice', $data);

        return $pdf->download('invoice.pdf');
    }
}

And the corresponding blade template resources/views/invoices/invoice.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Invoice</title>
</head>
<body>
    <h1>Invoice</h1>

    <h2>Invoice Number: {{ $invoice_number }}</h2>
    <h3>Customer: {{ $customer_name }}</h3>

    <table>
        <thead>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($items as $item)
                <tr>
                    <td>{{ $item['name'] }}</td>
                    <td>{{ $item['quantity'] }}</td>
                    <td>{{ $item['price'] }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>

    <p>Total: {{ $total }}</p>
</body>
</html>

This code generates a simple invoice PDF, but it lacks page numbers.

Adding Page Numbers

To add page numbers, we need to use Dompdf's built-in features. We can achieve this by adding a custom HTML snippet to the footer of our PDF. This snippet will use a page variable provided by Dompdf to display the current page number.

First, modify the resources/views/invoices/invoice.blade.php file by adding a footer section:

<!DOCTYPE html>
<html>
<head>
    <title>Invoice</title>
</head>
<body>
    <h1>Invoice</h1>

    <h2>Invoice Number: {{ $invoice_number }}</h2>
    <h3>Customer: {{ $customer_name }}</h3>

    <table>
        <thead>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($items as $item)
                <tr>
                    <td>{{ $item['name'] }}</td>
                    <td>{{ $item['quantity'] }}</td>
                    <td>{{ $item['price'] }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>

    <p>Total: {{ $total }}</p>

    <footer>
        <div style="text-align: right;">
            Page <span class="page-number"></span> of <span class="total-pages"></span>
        </div>
    </footer>
</body>
</html>

Next, update your generateInvoice() function in the controller:

use App\Http\Controllers\Controller;
use Barryvdh\DomPDF\Facade as PDF;

class InvoiceController extends Controller
{
    public function generateInvoice()
    {
        $data = [
            'invoice_number' => 'INV-1234',
            'customer_name' => 'John Doe',
            'items' => [
                ['name' => 'Product A', 'quantity' => 2, 'price' => 100],
                ['name' => 'Product B', 'quantity' => 1, 'price' => 50],
            ],
        ];

        $pdf = PDF::loadView('invoices.invoice', $data);

        // Set paper size and orientation
        $pdf->setPaper('A4', 'portrait');

        // Add page number and total pages
        $pdf->set_option('defaultFont', 'Arial');
        $pdf->set_option('isHtml5ParserEnabled', true);
        $pdf->set_option('isRemoteEnabled', true);
        $pdf->set_option('isFontSubsettingEnabled', true);
        $pdf->set_option('debugJavascript', true);

        $pdf->setOption('margin_bottom', 30); 

        $pdf->text('<span class="page-number"></span> of <span class="total-pages"></span>', 0, 277, 'right');

        return $pdf->download('invoice.pdf');
    }
}

This updated code sets options for dompdf and adds the page number to the footer.

Now, when you generate your invoice PDF, each page will display a page number in the footer.

Best Practices and Enhancements

Here are some additional tips for adding page numbers in your PDF documents:

  • Use CSS for Styling: Style the page numbers using CSS for consistency. You can create a separate stylesheet for your PDF and link it in your HTML.
  • Customize Placement: Experiment with different positions for the page numbers. You can place them in the header, footer, or even within the content itself.
  • Advanced Features: Dompdf supports a variety of advanced features, like headers and footers with multiple sections. Explore the Dompdf documentation for more complex layout options.

Conclusion

Adding page numbers to your PDF documents generated with Dompdf in Laravel is a simple yet essential enhancement. By understanding the Dompdf API and using custom HTML snippets, you can easily incorporate page numbers into your PDF generation process. This helps create more user-friendly and organized documents, improving the overall user experience.

Remember: Always test your implementation thoroughly and make sure your page numbers are displaying correctly across different PDF viewers.