Laravel PDF Generator Example | HTML To PDF | Download PDF Button

Laravel One To Many Relationship, laravel many to many relationship, laravel hasmanythrough, laravel one to many polymorphic, laravel one to one polymorphic, Laravel Many To Many Polymorphic Tutorial Example, laravel hasonethrough, Laravel PDF Generator

This tutorial will give you information about Laravel PDF Generator Example Tutorial.

We will learn how to create or generate a PDF file from html in laravel framework.

After creating PDF, we will also download this PDF file on the button click event.

In any laravel website, generating a PDF file from HTML is a common task and you need this functionality frequently.

For example, if you are creating any food ordering web site then you may need to generate PDF for final order summary or for any invoice in e-commerce websites.

Laravel does not provide any easy way to create PDF file so we will use one external composer package from github.

Youtube Output Video For this Tutorial

Step 1. Make a fresh laravel project

As always, our first step is to make a new laravel project using command line.

So trigger the below command in your terminal

laravel new larahtmltopdf

Above command will make a new laravel project and will set the name of the project as “larahtmltopdf

Step 2. Installing -dompdf Package in our Project

In this example, we will use external package or library called “laravel-dompdf

To integrate required files from this external library, you need to run the below command in your terminal

composer require barryvdh/laravel-dompdf

This command may take some time to download files from github to your local machine depending on your internet speed.

Once it finished process, 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. Adding lines in providers and Alias

After the successful installation of package, go to your config->app.php file.

You need to below lines 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,

So after adding both above lines, your app.php file should contain the following final code

<?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. Writing Route Lines

Navigate to routes->web.php file and add the below code lines

Route::get('htmlpdf','PDFController@htmlPDF');
Route::get('generatePDF','PDFController@generatePDF');

First line will open the html page which we will convert in to PDF file. When the user runs http://127.0.0.1:8000/htmlpdf in the browser, compiler will execute the htmlPDF() method from PDFController.php file. (We will create this file in next step)

Second line will create file when the user clicks the button. Compiler will execute this route and will call generatePDF() 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('htmlpdf','PDFController@htmlPDF');
Route::get('generatePDF','PDFController@generatePDF');

Step 5. Creating and Explaining Controller

Now it is time to create controller file. For this, run the below command in cmd

php artisan make:controller PDFController
This command will make a new file under app->Http->Controllers directory. Name of this file would be PDFController.php

Write down the below source lines in PDFController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    //
    public function htmlPDF()
    {
    
        return view('htmlPDF');
        
    }

    public function generatePDF()
    {
        $data = ['title' => 'Laravel HTML to PDF'];
        $pdf = PDF::loadView('htmlPDF', $data);
        return $pdf->download('demonutslaravel.pdf');
    }

}

This controller file have two methods. First one is htmlPDF()

In this htmlPDF() function, there is only one return statement. It is sending the controller to the htmlPDF.blade.php file. We will create this htmlPDF.blade.php file in the next step. This file contains the html text which we will convert into the PDF file.

Now second function is generatePDF()

First two lines of this function will load the view for PDF file. It is using htmlPDF.blade.php file as a view (see the second line) .

First line is defining the title and you can change it as per your requirements.

Last line is initiating the downloading process of PDF file. Here, you can set the name of the downloaded file. I have set it as “demonutslaravel.pdf

Step 6. HTML View File To Make PDF

Our final task is to make a blade view file. So navigate to resources->views directory and create a new file named “htmlPDF.blade.php” file.

You need to add the below lines of code in “htmlPDF.blade.php” file.

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 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="/generatePDF" 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 view as you have already seen in the youtube video at the starting of this tutorial.

I have added some html code and it is describing some basic information about Batman.

There is one button called “Generate PDF File” at the end of this view file. When you click this button, system will generate pdf file.

Download Source Code For This Example

https://github.com/demonuts/Laravel-HTML-to-PDF