Laravel 5.8 PDF Generator Tutorial Example | -dompdf

laravel send email, laravel 5.8 pdf generator, laravel send email gmail, laravel 5.8 gmail smtp

Welcome to laravel 5.8 pdf generator tutorial with example.

Today’s article will guide you how to generate PDF file from blade view or HTML in laravel 5.8 version.

In website development, you might need to generate PDF files in various cases like invoice generation, ticket booking confirmation etc.

This example will simplify these things for you. We will use one github external library to generate PDF file in laravel.

See the below video first.

 

Step 1. First Task as new Project

Let us create a new laravel project first. For this, trigger the following command in your terminal

laravel new larapdf58

Above command will make a new laravel project with name “larapdf58

Step 2. Installing External Library

After making a fresh new project, we need to install one library in our laravel project.

This github library will help us to make PDF files with few lines of source code lines.

You can find some more details about this github library here.

To integrate pdf library with our project, just run the following command

composer require barryvdh/laravel-dompdf

This command will download all the required files to your computer so, it will take some time depending on your internet speed.

Once the downloading process is finished, you should see the below lines in your terminal

Using version ^0.8.4 for barryvdh/laravel-dompdf
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing sabberworm/php-css-parser (8.1.0): Downloading (100%)
  - Installing phenx/php-svg-lib (v0.3.2): Downloading (100%)
  - Installing phenx/php-font-lib (0.5.1): Downloading (100%)
  - Installing dompdf/dompdf (v0.8.3): Downloading (100%)
  - Installing barryvdh/laravel-dompdf (v0.8.4): Downloading (100%)
dompdf/dompdf suggests installing ext-imagick (Improves image processing performance)
dompdf/dompdf suggests installing ext-gmagick (Improves image processing performance)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.

Step 3. Updating providers and aliases

After successful integration of library, we need to add some lines in config->app.php file.

So navigate to config->app.php file and add below line in ‘providers’ => [ … ] section of app.php file.

Barryvdh\DomPDF\ServiceProvider::class,

And then, write down the following source line in  ‘aliases’ => [ … ]  section of app.php file.

'PDF' => Barryvdh\DomPDF\Facade::class,

After adding both the lines, final source code for config->app.php file looks as the below

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Name
    |--------------------------------------------------------------------------
    |
    | This value is the name of your application. This value is used when the
    | framework needs to place the application's name in a notification or
    | any other location as required by the application or its packages.
    |
    */

    'name' => env('APP_NAME', 'Laravel'),

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services the application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG', false),

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => env('APP_URL', 'http://localhost'),

    'asset_url' => env('ASSET_URL', null),

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Faker Locale
    |--------------------------------------------------------------------------
    |
    | This locale will be used by the Faker PHP library when generating fake
    | data for your database seeds. For example, this will be used to get
    | localized telephone numbers, street address information and more.
    |
    */

    'faker_locale' => 'en_US',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    */

    'key' => env('APP_KEY'),

    'cipher' => 'AES-256-CBC',

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

        Barryvdh\DomPDF\ServiceProvider::class,

    ],

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Arr' => Illuminate\Support\Arr::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'Str' => Illuminate\Support\Str::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,

        'PDF' => Barryvdh\DomPDF\Facade::class,

    ],

];

Step 4. Route Related Tasks

To add a new routes, go to routes->web.php file and add the below code lines

Route::get('htmlpdf58','PDFController@htmlPDF58');
Route::get('generatePDF58','PDFController@generatePDF58');

First line is for opening of the HTML page.

When the user runs http://127.0.0.1:8000/htmlpdf58 in the browser, compiler will execute the htmlPDF58() method from PDFController.php file. (We will create this file in the next step)

Second line will create PDF file when the user clicks the button. Compiler will execute second line route and will call generatePDF58() method from controller file.

So the final code for routes->web.php file is looking like the below

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('htmlpdf58','PDFController@htmlPDF58');
Route::get('generatePDF58','PDFController@generatePDF58');

Step 5. Controller File and It’s functions

For making controller file, run the following line in terminal

php artisan make:controller PDFController

You should now navigate to app->Http->Controllers directory. Here, you will find a file named PDFController.php

Source snippet for PDFController.php file is at the below

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    //
    public function htmlPDF58()
    {
    
        return view('htmlPDF');
        
    }
 
    public function generatePDF58()
    {
        $data = ['title' => 'Laravel 5.8 HTML to PDF'];
        $pdf = PDF::loadView('htmlPDF', $data);
        return $pdf->download('demonutslaravel.pdf');
    }
}

This file have two functions. Let us understand first function which is htmlPDF58()

It has one return statement. This return statement sends the compiler to the htmlPDF.blade.php file. We will create this balde view file in the next step.

Now focus on the second function. It is generatePDF58() 

First line of this function is giving the title to the PDF file. You can set any title in this line.

Second line is loading a view which is again htmlPDF.blade.php file. Meaning is that system will convert htmlPDF.blade.php file into the PDF file.

Last line will initiate the downloading process. Here, we can set the name of the file which will be downloaded into the user’s web browser. I have set the name as “demonutslaravel.pdf

Step 6. Making the Last Blade file

At last, we need to make one blade view and we are done with this tutorial.

So move to the resources->views directory and create a new file named “htmlPDF.blade.php” file.

Write down the below source code lines in “htmlPDF.blade.php” file.

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 5.8 HTML to PDF</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
 
    <h1 > Who is Batman ? </h1>
	
 
<p>
 
	Batman is a fictional superhero appearing in American comic books published by DC Comics. 
    The character was created by artist Bob Kane and writer Bill Finger,[1][2] and first appeared in Detective Comics #27 in 1939. 
    Originally named the "Bat-Man," the character is also referred to by such epithets as the Caped Crusader, the Dark Knight, and the World's Greatest Detective.
 
Batman's secret identity is Bruce Wayne, a wealthy American playboy, philanthropist, and owner of Wayne Enterprises. After witnessing the murder of his parents Dr. Thomas Wayne and Martha Wayne as a child, he swore vengeance against criminals, an oath tempered by a sense of justice. Bruce Wayne trains himself physically and intellectually and crafts a bat-inspired persona to fight crime.[6]</p>
 
<form method="GET" action="/generatePDF58" enctype="multipart/form-data">
<div class="form-group">
 
 <div class="control">
 
     <button type="submit" class="btn btn-primary">Generate PDF File</button>
 
 </div>
 
</div>
 
</form> 
 
</body>
</html>

This file create a look and feel with HTML code. We will convert this HTML code into PDF file.

Let us concentrate on below source code

<form method="GET" action="/generatePDF58" enctype="multipart/form-data">
<div class="form-group">
 
 <div class="control">
 
     <button type="submit" class="btn btn-primary">Generate PDF File</button>
 
 </div>
 
</div>
 
</form>

I have added one button inside a form tag. When the user clicks this button, compiler will execute the generatePDF58() method from PDFController.php file.

Download Source Code

Click the below link to download the full source code

https://github.com/demonuts/Laravel-5.8-PDF-Generator-Tutorial-Example