3 Feb, 2019

Creating a PDF in Laravel

Create a new project with the following Command:

composer create-project --prefer-dist laravel/laravel pdf

Now we need to install a DOMPDF Wrapper package in our project.

composer require barryvdh/laravel-dompdf

After updating composer, add the ServiceProvider to the providers array in config/app.php

Barryvdh\DomPDF\ServiceProvider::class,

You can optionally use the facade for shorter code. Add this to your facades:

'PDF' => Barryvdh\DomPDF\Facade::class,

Now, create a new controller.

php artisan make:controller PDFMakerController

We need to add route.

Route::get('/download', 'PDFMakerController@make')->name('pdf');

Now we need to work on our PDFMakerController.

public function make(){ $data =
[
'title' => 'Invoice 2128',
'total' => '679',
'products' => ['jhutta', 'mojha', 'topi']
];
$pdf = PDF::loadView('pdf.invoice', $data); return $pdf->download('invoice.pdf');
}

Create a new folder and file i.e. inside views folder. views/pdf/invoice.blade.php. Now go to invoice.blade.php and use the following code.

<h1>{{$title}}</h1> 
<p>{{$total}}</p> 
@foreach($products as $product)
<p>{{$product}}</p>
 @endforeach

Now,

php artisan serve

And go to 127.0.0.1:8000/download