Dec 28, 2021

HTML to PDF with Laravel

Learn how to convert HTML to PDF with our Laravel package

Sometimes it might be useful to turn some HTML into a PDF eg for generating order confirmations or invoices. With some libraries it might be painful to generate a nice looking PDF, when you have to place text and/or images through PHP code. But Websnap’s Laravel package allows us to use our existing HTML/CSS knowledge and create a PDF from HTML/CSS with ease.

Summary

In our example we will create a downloadable order confirmation PDF to an existing list of orders.

  1. Install Websnap’s Laravel package
  2. Register confirmation route
  3. Set the link’s href to the new route

Install Websnap’s Laravel package

First of all we have to require Websnap’s Laravel package via composer. To do this we run composer require websnap/laravel in Laravel’s root directory.

If you haven’t created an account yet, you can register for free and obtain a project token. Copy the token and paste it as an environment variable to your .env file.

WEBSNAP_TOKEN={YOUR_TOKEN}

Register confirmation route

To do this we have to register a new route in our web.php file which will render our confirmation view and send the HTML through Websnap’s PDF API.

Route::get('orders/{order}/confirmation', function (\App\Models\Order $order) {
    return response()->pdf(
        view('orders.confirmation'),
        compact('order')
    );
})->name('order-confirmation');

For convenience, the Laravel Websnap package adds a pdf macro to the response factory to return a pdf response.

Set the link's href to the confirmation route

After we have registered the route and styled the confirmation view, we only have to add the new route as the target to our links. In addition we can add the download attribute to prompt the user to save the linked PDF instead of navigating to it.

<a
    href="{{route('order-confirmation', $order)}}"
    download="Order #{{$order->increment_id}} - Confirmation"
>
    Download Confirmation
</a>

That’s it! You can pull this example from our GitLab repository and fiddle around with it.

Caveats

Since Websnap will load all linked resources like images or stylesheets, we have to make sure that those files are available to the public internet, which might not be the case when developing locally. As an alternative we can also inline some resources like css style instructions.

<style>{!! file_get_contents(public_path('css/app.css')) !!}</style>

Conclusion

Websnap's PDF API makes it easy to convert HTML to PDF with Laravel or PHP.

Please feel free to get in touch if you have any further questions.