How to Make a PDF from View in Laravel? | How to generate pdf using blade view with dompdf in laravel?
In this session we gonna a make a very cool thing. Sometimes we need to generate Pdf for creating report or to show data into document . So today we are gonna convert a static view page to pdf using Laravel.
1. In the first process we gonna install a package called /laravel-dompdf
It's very easy to install in your project. Just go through the doc and have installed it.
If you can't install in your project, Just ping me in comment.
2. Then create a route in Route.php
Route::get('/pdf', [
'uses' => 'courseController@createPdf',
'as' => 'pdf'
]);
3. Then create a Controller :
public function createPdf()
{
$alldata=Course::all(); // it'll load all the data from course model.
$pdf = \PDF::loadView(
'invoice', compact('alldata'))->setPaper('a4')->setOrientation('portrait');
return $pdf->download('invoice.pdf');
}
And don't forget to use namespace above the the controller otherwise it will show Error.
namespace we have to use:
use Barryvdh\DomPDF\Facade as PDF;
4. In controller you save seen that in that loadView('invoice') (It's actually a view page which will generate the PDF). So we have to create first this view page where we can show all the data what a user wanted to see.
5. That's it so when the user click on that pdf route, it will automatically generate/ convert the page into PDF.
That's it for today. Hope you liked it. If you want me to post more tutorial on laravel don't forget to comment or feedback.
Thank you.
0 comments:
Post a Comment