shanechrisbarker.co.uk

Creating PDF's with Laravel

Published On: Saturday 12th of January 2019 15:15:46

PDF files

So, you need to build a PDF with Laravel eh?

Creating a PDF is quite a common thing for web application to do. Whether it's a static file like a food menu or a dynamically created PDF for an invoice or similar, PDF's are used everywhere.

In this tutorial, we'll create a PDF using Laravel and a package called MPDF.

We'll create a form and use it to catch some information. Next, we'll send that information to a Controller, generate the PDF and send it to the users browser.

For this tutorial, we'll say we want to take a users name and email address via a form and then use this data to generate a 50% off coupon as a PDF.

Step 1: Install MPDF

To begin with, we'll need to install the MPDF library into our application. This is done via Composer so open up a terminal in the root of your application and run:

composer require mpdf/mpdf
This will add MPDF to your composer.json file and make it availble for use in your application.

Step 2: Create the routes

The next thing we'll need is some routes. Open up your applications routes/web.php and add the following lines to it:

Route::get('/pdf/form', 'PdfDemoController@index');
Route::post('pdf/form', 'PdfDemoController@createPdf')->name('pdf.create');
The POST route will handle our form submission and the GET will handle showing the view containing our form.

Step 3: Create the Controller and the index function

With our routes added, we'll go ahead and create the PdfDemoController that our routes call. go back to your terminal and type the following command:

php artisan make:controller PdfDemoController

This will create a PdfDemoController located at app/Http/Controllers. Open it up and add the following code:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PdfDemoController extends Controller
{
    public function index()
    {
        return view('pdf-form');
    }

Step 4: Create the view and the form

It's now time to create the view that our index() function returns. This view is where we will put our form code. Create a file at resources/views called pdf-form.blade.php and add the following code to it:

Please Note:

I'm using Bootstrap 4 in my application as can be seen by the classes used in the form. If you're not using Bootstrap, your form will look different to the screenshot below

Enter your details to receive a free coupon!

Coupon is valid for 30 days and gets the holder 50% off food at any branch of Shanie's

{{Form::open(['route' => 'pdf.create'])}}
{{Form::label('name', 'Please Enter your name', ['class' => 'col-5 form-label'])}} {{Form::text('name', null, [ 'placeholder' => 'E.G John Smith', 'class' => 'col-7 form-control', 'required' => 'required' ] )}}
{{Form::label('email', 'Please enter your email', ['class' => 'col-5 form-label'])}} {{Form::email('email', null, [ 'class' => 'col-7 form-control', 'placeholder' => 'E.G you@yourEmail.com', 'required' => 'required' ] )}}
{{Form::submit('Get Your Coupon!', ['class' => ['btn btn-primary col-4 offset-4']])}}
{{Form::close()}}

If you now browse to /pdf/form in your application, your form should render.
our finished form should look something like this:

Our form for capturing our users data

Step 5: Adding the createPdf function

The last step with our controller is to create the createPdf() function that our form will submit to. Open up the PdfDemoController and add the following code so it now looks like this:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mpdf\Mpdf;

class PdfDemoController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function createPdf(Request $request)
    {
        // Get the input that our form posted
        $input = $request->input();
        // Instantiate Mpdf
        $mPdf  = new Mpdf();

        // Create a new DateTime object and set a variable equal to 30 days from
        // today. This will be the valid till date on our voucher.
        $dateTime   = new \DateTime();
        $dateTime->add(new \DateInterval('P30D'));
        $validTillDate = $dateTime->format('m-d-Y');

        // Create a view along with the variables we need and store it into
        // the $pdfView variable
        $pdfView = \View::make('voucher')
            ->with('name', $input['name'])
            ->with('email', $input['email'])
            ->with('valid_date', $validTillDate);

        // Write the PDF using the html we just made
        $mPdf->writeHTML($pdfView->render());
        // output to the browser for download.
        $mPdf->output('shanies-coupon.pdf', \Mpdf\Output\Destination::DOWNLOAD);
        // all done - we can now send our user back.
        return redirect()->back();
    }
}

Step 6: Creating the PDF html

As you can see in the createPdf() function, we use \View::make() to create and assign a view to a variable before passing this to MPDF for processing. The final step is to create that view.

Create a new file called voucher.blade.php located at resources/views and add the following code to it:


50% off Food at Shanies with this voucher!

This voucher entitles the holder to 50% off any food order at any branch of Shanie's

Voucher Holder Name: {{$name}}

Voucher Holder Email: {{$email}}

Valid till: {{$valid_date}}

Please Note:

MPDF doens't support Bootstrap and can be restrictive on which CSS it does honour.

For a full list of supported CSS properties, you should check out the official MPDF manual, which can be found here.

And with that, we're done. If you now fill in and submit your form and your PDF should be downloaded to your browser: Our generated PDF