Posted on / by Vivan Web Solution / in Laravel Development / 23 comments

How to create pdf in Laravel 5?

In this article, I will Show you how to create pdf in Laravel 5.

Step 1: 

Install the composer package for pdf in project directory using this command.
composer require barryvdh/laravel-dompdf

Step 2:

Configure this package in app/config.php and add the following code.

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

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

Step 3:

Now create route  in route/web.php  and add the following code.

Route::get('pdfview',array('as'=>'pdfview','uses'=>'PolicyController@pdfview'));

Step 4:

Add code in controller app/Http/Controllers/PolicyController.php.

class PolicyController extends Controller
{
public function pdfview(Request $request)
{
$items = DB::table("items")->get();
view()->share('items',$items);
if($request->has('download')){
$pdf = PDF::loadView('pdfview');
return $pdf->download('pdfview.pdf');
}
return view('pdfview');
}
}

Step 5: 

Now create a blade file for PDF data.
Open file resources/view/admin/policy/pdfview.blade.php  and add the following code.

<a href="{{ route('pdfview',['download'=>'pdf']) }}">Download PDF</a>
<table>
<tr>
<th>No</th>
<th>Policy Name</th>
<th>Policy Category</th>
</tr>
@foreach ($items as $key => $item)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->category }}</td>
</tr>
@endforeach
</table>

Thanks For Reading this article. I hope it will help you.

23 thoughts

Leave a Reply

×