We can easily generate PDFs in Laravel using the package barryvdh/laravel-dompdf
. To install it
to an application, just run the command —
After installing the package, we need to add it to providers array
in config/app.php
as
BarryVdh\Barryvdh\DomPDF\ServiceProvider::class
.
Now we need to create a blade template that would be used as a markup for the PDF that we want to generate. Let’s say our template looks like —
As you can see, the above template just displays a hello world message. To generate a PDF using this template, the controller would be —
To render the the generated PDF in the browser using the file url, we need create a controller like —
Now if we go to the url /pdfs/filename.pdf
, we can see the generated PDF.
To pass data to the PDF template, we can just pass an array as the second argument of loadView
. The code
snippet shown below can be taken as a reference for this —
Let’s now try adding image assets to the PDF. We pass a image
field to the data array passed to loadView
and pass filesystem image to our PDF template. On rendering the generated PDF, we’ll see a
Image not found or type unknown error.
This is because the package only supports base64 encoded images.
To fix the issue, we can create an utility function to encode any image passed to the PDF template to base64
format. Let’s use the @php
directive to create a function in the template itself. The code snippet below can
be taken as a reference for this —
Finally, if you check the PDF rendered after encoding the image, we can see it in the PDF.