Often in your projects you will come across a requirement of converting your view file into PDF. In this article we will cover a tutorial on how we can easily convert view file into PDF using NitMedia/wkhtml2pdf package.
Follow the Steps to Generate the PDF
Install Composer Package.
Open composer.json
file located at the project root of your application and add the following package at require parameter
"require": { .. .. .... "nitmedia/wkhtml2pdf": "dev-master", },
Run the Composer update comand
composer update nitmedia/wkhtml2pdf
Add Service Provider
Once composer update is completed, we will have the required file dependencies in our project. Let’s go ahead and add the ServiceProvider provided by the package in our config/app.php file
'providers' => [ .... ... .. Nitmedia\Wkhtml2pdf\L5Wkhtml2pdfServiceProvider::class, ],
At the end of config/app.php
add 'PDF' => 'Nitmedia\Wkhtml2pdf\Facades\Wkhtml2pdf'
to the $aliases
array
'aliases' => [ .... ... .. 'PDF' => Nitmedia\Wkhtml2pdf\Facades\Wkhtml2pdf::class, ],
Publish Vendor
Finally, Publish the vendor file, Run the vendor:publish command
php artisan vendor:publish
This command will generate a new file Wkhtml2pdf.php
under the applications config directory. This file contains the driver to be used for PDF generation. Set the driver file accoridng to the current OS, Supported drivers include: mac osx, linux 32, linux 64
Generating PDF Files
We are now all set to generate or download PDF files in Laravel using this helpful package.
Lets create a necessary route and controller method to demonstrate the PDF generation.
Open your web.php file under routes directory and add the following route.
Route::get('/testpdf','HomeController@GeneratePDF');
Open HomeController.php
located at App/Http/Controllers
and add the following method.
public function generatePDF(){ $users = User::all(); return PDF::html('testpdf',array('users' => $users)); }
In this Controller method we are getting all the users from the database table and passing it on to the view file to be included in the PDF.
Let’s create a sample view file in resources/views
folder named testpdf.blade.php
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">PDF Report</div> <table class="table"> <tr> <th>Name</th> <th>Email</th> <th>Created At</th> </tr> @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->created_at }}</td> </tr> @endforeach </table> </div> </div> </div> </div> @endsection
We are displaying all the user’s in a HTML table. A PDF file is generated when you visit the /testpdf page of your application.
Laravel PDF ExampleIf you want to force download the PDF File in Laravel using this package then do the following
PDF::setOutputMode('F'); // force to file PDF::html('app.invoices.pdf',['title'=>$title],'/var/www/test.pdf'); //Custom download path