How to create PDF in Laravel 7

Laravel is a framework of PHP and is widely used. Creating a PDF in PHP or say Laravel is a pretty common thing. There are various libraries available for creating PDF in laravel. So let’s see how to create PDF in laravel 7. Don’t worry it will also work in laravel 5 and 6.

I am assuming you have the setup of laravel project if not then follow this article to set up a new laravel project. So the library I am going to use to create PDF in this article is laravel-dompdf.

Let’s get started then, open terminal or cmd in your project directory of laravel and type the following command to install a laravel-dompdf package.

composer require barryvdh/laravel-dompdf

Now this package is installed into your project. The next step is to register this package with your project. To do that you have to make some changes in “config/app.php“.

Open “config/app.php“, find the following and append this at the end of the providers array.

...
'providers' => [
...
Barryvdh\DomPDF\ServiceProvider::class,
],

Well, the laravel-dompdf package is registered in your project, now you can access its instance anywhere in the project. But instead of Barryvdh\DomPDF\ServiceProvider writing this line on every page, we can just alias its facade to use a shorter name. To do that, in the same file find aliases array and add below line to end of the array.

...
'aliases' => [
...
'PDF' => Barryvdh\DomPDF\Facade::class,
],

Now we can simply use this package as PDF in any file like this.

use PDF;

So open Controller, helper file, or anywhere you want to create pdf and add the following code. Do not forget to use use PDF on top of the file.

$pdf = PDF::loadView('viewfilename');
 return $pdf->download('invoice.pdf');

Probably these two lines of code can confuse you for now. Let’s take a look at the first line $pdf = PDF::loadView('welcome'); , we are calling loadview() a static function that is accepting one string parameter and this parameter is nothing but your view file name.

Then in the second line, we are downloading the file with download() a function that also accepts one parameter but this time it is understandable that it is the file name.

Note: To pass dynamic data to view you can pass the second parameter to loadView() function.

Creating dynamic PDFs

$data = User:all();
$pdf = PDF::loadView('viewfilename',$data);
 return $pdf->download('invoice.pdf');

For reference.

How to create PDF in Laravel 7

So that’s all about how to create PDF in laravel. Hope this article has helped you. If you still find something hard, feel free to ask in the below comment box.

see also

Leave a Reply

Your email address will not be published. Required fields are marked *