Last updated on February 17, 2018
We gonna use barryvdh/laravel-dompdf
Laravel package to generate PDF files from view file. This package is just a wrapper around DOMPDF
library.
Installtion
Use below composer command to install the package
composer require barryvdh/laravel-dompdf
After installing laravel-dompdf
, add the ServiceProvider class to the provider’s array in config/app.php
'providers' => [ Barryvdh\DomPDF\ServiceProvider::class ];
You can optionally use the facade for shorter code. So when you need to generate PDF you just need to include it with use PDF
, you dont have to metion full namesapce. Add this to your facades array in config/app.php
'aliases' => [ 'PDF' => Barryvdh\DomPDF\Facade::class ]
Great! installation and configuration part is completed. Now let use this package.
Generate a controller called UserController.php
with below command
$ php artisan make:controller UserController
After generating controller add following index
and report
methods to it. Index is to show the list of users and report is to generate PDF and to download the PDF.
$users]); } public function report(Request $request) { $users = User::all(); if($request->view_type === 'download') { $pdf = PDF::loadView('users.report', ['users' => $users]); return $pdf->download('users.pdf'); } else { $view = View('users.report', ['users' => $users]); $pdf = \App::make('dompdf.wrapper'); $pdf->loadHTML($view->render()); return $pdf->stream(); } } }
Create a users
directory with index.blade.php
and report.balde.php
files.
index.blade.php
Laravel Download PDF view PDF
@foreach ($users as $user) Name @endforeach {{ $user->name }} {{ $user->email }}
report.blade.php
Laravel
@foreach ($users as $user) Name @endforeach {{ $user->name }} {{ $user->email }}
Now define route to access controller methods index and report, add follwing lines to routes/web.php
Route::get('/users', 'UserController@index'); Route::get('/users/report/{view_type}', 'UserController@report');
That’s it. Now, with http://localhost:8000/users/report/view, you can render pdf in the browser, with http://localhost:8000/users/report/download
you can download the user’s list pdf.