How to Generate PDF in Laravel 10 with DOMPDF

Last Updated on by in Laravel

Welcome to our site, If you want to create or generate documents like invoices, reports, forms, and other content that needs to be downloaded, printed, or shared in PDF format. You’re in luck!

In this guide, we’ll go through the steps of creating a PDF file in Laravel 10 using the DomPDF library.

Generating PDFs is a common need for many web applications. Laravel provides an easy way to accomplish this using the DomPDF library. Let’s explore what DomPDF is before we proceed with the steps to programmatically generate a PDF file in Laravel.

What is DomPDF Laravel?

The DomPDF package provides a simple and convenient way to create, generate and download PDF documents from HTML content in Laravel. It supports the latest version of PHP and help you customize PDF document within Laravel.

Let’s find out how to streamline the process of adding PDF generation functionality to web applications built using Laravel framework.

Install Laravel Project

For Laravel export to PDF demo example we require to download a fresh laravel app.

Run the command to induct fresh Laravel project.

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

Install DomPDF Library

Run the under-mentioned command to install DomPDF in Laravel.

composer require barryvdh/laravel-dompdf

Configure DomPDF Package in Laravel

Open config/app.php file and incorporate 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,
]

Execute the following command to publish the assets from vendor.

php artisan vendor:publish

A handful of packages list appeared on your terminal window, and we have to 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.

Ultimately, you can take the DomPDF in service to convert HTML to PDF File in Laravel using the following attribute.

use PDF;

Setting Up Model and Migrations

Create a new Model for Employee using the given below command.

php artisan make:model Employee -m

Open app/Employee.php file, and place the following code.

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

Execute the following command to migrate the database values, verify the table created with the values mentioned above in the MySQL database.

php artisan migrate

Generate Fake Data

We will create fake users list and show you how to generate PDF, to create fake data we need to use Faker package. It is a PHP library that generates fake data for you.

Head over to database/seeds/DatabaseSeeder.php and insert the following values that matches with 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 command to generate the fake data.

php artisan db:seed

Check database table in PHPMyAdmin, you will see 10 new records have been generated for employees table.

Define Controller & Route

Please create a new controller, and It will have the logic to display the user’s list. Run the command to create the controller.

php artisan make:controller EmployeeController

Open app/Http/Controllers/EmployeeController.php and add the following code.

<?php

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

use App\Models\Employee;

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

Display Users List in Blade View Template

Generate a blade file resources/views/index.blade.php then insert the following code inside. The user records are fetched from database and being displayed in the laravel blade view temlpate using Bootstrap Table module.

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

Generate PDF in Laravel with DOMPDF

Download PDF in Laravel

Now, we will learn how to export HTML to PDF and fetch users list from database and display in the PDF file format in Laravel.

Head over to app/Http/Controllers/EmployeeController.php and define the createPDF() function. This function will fetch all the records from the database, share users data with PDF blade template and, allow downloading the PDF file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\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');
    }
}

Define Route

Open routes/web.php and insert the following code. It will create relation between the controller & the view over and above that it will also invoke the pdf download.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;

/*
|--------------------------------------------------------------------------
| 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('/', [EmployeeController::class, 'showEmployees']);

Route::get('/employee/pdf', [EmployeeController::class, 'createPDF']);

In the end, we have to add the following button above the table inside the index.blade.php. It will 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-mentioned command to run the Laravel PDF project.

php artisan serve

Explore app on http://127.0.0.1:8000

Conclusion

Whether you are a Laravel beginner seeking help in HTML-to-PDF conversion or an experienced PHP developer willing to convert simple HTML strings or data into a well-formatted PDF document, with this how-to guide, you can generate dynamic and customizable PDF files in Laravel.