How to Generate PDF File in Laravel 9 with DOMPDF

This is a step by step tutorial, In this tutorial we we will guide you on how to export table data to PDF in Laravel application. We will learn to use the DomPDF library and also look at how to generate PDF from HTML.

We will create a user list in a table and this table will show all the dynamic user lists which is coming from the database.

Then, we will teach you how to export the table format in a PDF file.

Setup the Laravel Project

We will install the new laravel project.

Run the below command to install the new Laravel project.

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

Head over to the project folder:

cd laravel-pdf

Setup the DomPDF Package

Among all the available third party ‘HTML to PDF’ conversion tool in laravel DomPDF is decisive choice.

DOMPDF is a great library and it is capable of generating a PDF from HTML.

Run the below command to install DomPDF in Laravel.

composer require barryvdh/laravel-dompdf

Setup DomPDF Package in Laravel

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,
]

Run the following command to publish the assets from vendor.

php artisan vendor:publish

Some useful packages list appeared on you terminal window and we will select the “Provider: Barryvdh\DomPDF\ServiceProvider” option from the list. It 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;

Setting Up Model and Migrations

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'];

}

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');
    }
}

Run the following command in order to relocate database values, check the table made with the qualities referenced above in the MySQL database.

php artisan migrate

Create Fake 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 fake 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.

Go to database/seeds/DatabaseSeeder.php and put the following values that match 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')
            ]);
        }
    }
}

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.

Create A Controller & Route

Create a new controller to display the user’s 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'));
    }
}

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');

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 7 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>

Download PDF File

Now, we are going to guide you about how we can 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');

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 7</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>

Start Laravel Application

Run the below command to run the Laravel PDF project.

php artisan serve

Explore app on http://127.0.0.1:8000