Generate PDF File in Laravel 8 with DOMPDF - Step by step guide ?

Generate PDF File in Laravel 8 with DOMPDF - Step by step guide ?

Most E-commerce projects, Shopping websites, E-Marketing Websites require a function to generate invoices, acknowledgment, tickets and so on. PDF is one of basic requirement when you are working with ERP level project or e commerce website. Sometimes, we may need to create pdf file for report or invoice etc.
Here at Fixwebnode , as part of our Website Development Services, we regularly help our Customers to fix related Laravel Application queries.
In this context, we shall look into how to export table data to PDF in Laravel 8 application with the DomPDF library.

Steps to Generate PDF File using DomPDF in Laravel

1. Create new Laravel 8 Application 
You need to run the below command to create the new Laravel project (laravel-pdf):


$ composer create-project laravel/laravel laravel-pdf --prefer-dist



Then, move into the project folder with the below command:


$ cd laravel-pdf


 

2. Set up the DomPDF Package
DomPDF is a third party 'HTML to PDF' conversion tool with a great library and it is capable of generating a PDF from HTML. 
You can run the below command to install DomPDF in Laravel:


$ composer require barryvdh/laravel-dompdf


 

3. Set up DomPDF Package in Laravel
Here, Open config/app.php file and include DomPDF service provider in providers array along with DomPDF facade to the aliases array:


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

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



Then, Run the following command to publish the assets from vendor:


$ php artisan vendor:publish



You will see Some useful packages list on the terminal window and you shouldselect the "Provider: Barryvdh\DomPDF\ServiceProvider" option from the list. This will create the new file config/dompdf.php, holding global configurations for the DomPDF plugin.
You can take the DomPDF in service to convert HTML to PDF File in Laravel using the below code:


use PDF;


 

4. Set up Model and Migrations
Here, Create a new Employee Model:


$ php artisan make:model Employee -m



Add the below code in app/Employee.php file:


<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model {

   public $fillable = ['name', 'email', 'phone_number', 'dob'];

}



Then, Open database/migrations/timestamp_create_employees_table.php and add the form values that we would store in the database:


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeesTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('employees', function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('name');
           $table->string('email');
           $table->string('phone_number');
           $table->string('dob');
           $table->timestamps();
       });
   }

   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::dropIfExists('employees');
   }
}


Next, relocate database values, check the table made with the qualities referenced above in the MySQL database by running the below command:


$ php artisan migrate


 

5. Create Demo User's Data
Now, we need the list of users and show you how to generate PDF, and, to do this we will use the demo user's list, and to create the fake user's list, we will use the Faker package. It is a PHP library that generates fake data.
Start by going to database/seeds/DatabaseSeeder.php and put the following values as per your data table:


<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{

   public function run() {
       $faker = Faker::create();

    foreach (range(1,10) as $index) {
           DB::table('employees')->insert([
               'name' => $faker->name,
               'email' => $faker->email,
               'phone_number' => $faker->phoneNumber,
               'dob' => $faker->date($format = 'D-m-y', $max = '2000',$min = '1990')
           ]);
       }
   }
}


Then, Run the below command to generate the fake data:


$ php artisan db:seed


Go to PHPMyAdmin, and, you will see that, database table has been updated with the new 10 employees records.

 

6. Create A Controller & Route
Create a new controller to display the users list.
Run the below command to create the controller:


$ php artisan make:controller EmployeeController


Add the following code in app/Http/EmployeeController.php:


<?php

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

use App\Employee;

class EmployeeController extends Controller
{
   public function showEmployees(){
     $employee = Employee::all();
     return view('index', compact('employee'));
   }
}


 

7. Define Route for Showing Employee List
Now, we will make the relation between the controller and the view. To do this, open routes/web.php and add the below code:


Route::get('/', 'EmployeeController@showEmployees');


 

8. Create Blade File & Display Users List
Create a blade file resources/views/index.blade.php then add the following code. The user records are directly coming from the database and displayed in the blade view template file:


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Laravel 8 PDF Example</title>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
   <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
   <div class="container mt-5">
       <h2 class="text-center mb-3">Laravel HTML to PDF Example</h2>

       <div class="d-flex justify-content-end mb-4">
           <a class="btn btn-primary" href="{{ URL::to('#') }}">Export to PDF</a>
       </div>

       <table class="table table-bordered mb-5">
           <thead>
               <tr class="table-danger">
                   <th scope="col">#</th>
                   <th scope="col">Name</th>
                   <th scope="col">Email</th>
                   <th scope="col">Phone</th>
                   <th scope="col">DOB</th>
               </tr>
           </thead>
           <tbody>
               @foreach($employee ?? '' as $data)
               <tr>
                   <th scope="row">{{ $data->id }}</th>
                   <td>{{ $data->name }}</td>
                   <td>{{ $data->email }}</td>
                   <td>{{ $data->phone_number }}</td>
                   <td>{{ $data->dob }}</td>
               </tr>
               @endforeach
           </tbody>
       </table>

   </div>

   <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>

</html>


 

9. Download PDF File
Now, you will see how to export HTML to PDF and fetch the user's list from the database then display in the PDF file format in Laravel.
Now, one of the most important parts is to define the createPDF() function and this function helps in fetching all the records from the database and the share user's data with the PDF blade template and, allows downloading the PDF file. To do this, go to app/Http/EmployeeController.php and define the function:


<?php

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

use App\Employee;
use PDF;

class EmployeeController extends Controller {

   // Display user data in view
   public function showEmployees(){
     $employee = Employee::all();
     return view('index', compact('employee'));
   }

   // Generate PDF
   public function createPDF() {
     // retreive all records from db
     $data = Employee::all();

     // share data to view
     view()->share('employee',$data);
     $pdf = PDF::loadView('pdf_view', $data);

     // download PDF file with download method
     return $pdf->download('pdf_file.pdf');
   }
}


Create a new route in routes/web.php file; it will handle the pdf download:


Route::get('/employee/pdf','EmployeeController@createPDF');


 

10. Create a new PDF Blade View Template
Create a template views/pdf_view.blade.php, add the below code inside of it:


<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>PDF Demo in Laravel 8</title>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
 </head>
 <body>
   <table class="table table-bordered">
   <thead>
     <tr class="table-danger">
       <td>Name</td>
       <td>Email</td>
       <td>Phone Number</td>
       <td>DOB</td>
     </tr>
     </thead>
     <tbody>
       @foreach ($employee as $data)
       <tr>
           <td>{{ $data->name }}</td>
           <td>{{ $data->email }}</td>
           <td>{{ $data->phone_number }}</td>
           <td>{{ $data->dob }}</td>
       </tr>
       @endforeach
     </tbody>
   </table>
 </body>
</html>


Inside index.blade.php add the following button, it would allow users to export HTML into PDF:


<a class="btn btn-primary" href="{{ URL::to('/employee/pdf') }}">Export to PDF</a>


 

11. Start Laravel Application
Run the below command to run the Laravel PDF project:


$ php artisan serve



Then, Explore app on http://127.0.0.1:8000.

 

[Need assistance in fixing Laravel Application issues ? We can help you. ]


Conclusion

This article covers how to generate pdf in laravel 8 using DomPDF. In fact, Dompdf is a query based on the Laravel framework that will help generate a pdf file. It can be integrated in any environment, based on a Laravel framework. Dompdf makes things easier for the developer to create queries for generation of pdf. With laravel-dompdf, one can easily go ahead create downloadable pdf file.


icon

Sign up to our Newsletter

...and get one free support ticket.