How to Generate Dynamic PDF from HTML in Laravel

Dynamic PDF is need for create commercial web application. In this example we will learn generate dynamic PDF from HTML in laravel . We generate dynamic pdf from html using laravel dompdf library.

Laravel dompdf in most popular library for generate dynamic pdf in your website. PDF in one of the basic requirement whene you create ecommerce website and you can create report or invoices.

In this example we will explain step by step how to generate dynamic PDF from html view in laravel application.

In this example we will install laravel domdpf (  barryvdh/laravel-dompdf ) library using the composer. So let’s following step to install dompdf library in your laravel application.

Laravel generate dynamic pdf from html using dompdf library

Step 1: Install Laravel

In this step we will install laravel fresh package for generate dynamic pdf from html view. So let’s following commands:

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

Step 2: Install laravel-dompdf Library

In this step we will install laravel barryvdh/laravel-dompdf composer package by using the following command:

composer require barryvdh/laravel-dompdf

After install the laravel dompdf library open config/app.php file and add service provider and alias.

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

Step 3 – Create Controller

In this step we will create controller for generate dynamic pdf from html view. So following command to create controller:

php artisan make:controller DisneyplusController

This command will make controller in app/Http/Controllers folder with name like DisneyplusController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Disneyplus;
use PDF;

class DisneyplusController extends Controller
{
    public function index()
    {
        $shows = Disneyplus::all();
        return view('list', compact('shows'));
    }

    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }

    public function downloadPDF($id) {
        $show = Disneyplus::find($id);
        $pdf = PDF::loadView('pdf', compact('show'));
        
        return $pdf->download($show->show_name.'.pdf');
    }
}

Step 4 – Create view file

In this step we will create view files for generate dynamic pdf from html using in laravel.

Read Also :  Laravel Firebase Push Notification Example

layout.blade.php

<!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/6 CRUD Example</title>
  <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="container">
    @yield('content')
  </div>
  <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>

form.blade.php

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

list.blade.php

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{route('downloadPDF', $show->id)}}">Download PDF</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

pdf.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <table class="table table-bordered">
    <thead>
      <tr>
        <td><b>Show Name</b></td>
        <td><b>Series</b></td>
        <td><b>Lead Actor</b></td>     
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>
          {{$show->show_name}}
        </td>
        <td>
          {{$show->series}}
        </td>
        <td>
          {{$show->lead_actor}}
        </td>
      </tr>
      </tbody>
    </table>
  </body>
</html>

Step 5: Create Model and Migration

In this step we will create Model and Migration for generate dynamic pdf from html in laravel application. So let’s following commands:

php artisan make:model Disneyplus -m

Model : Disneyplus.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Disneyplus extends Model
{
    use HasFactory;

    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Migration : 2021_03_19_155714_create_disneypluses_table.php

<?php

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

class CreateDisneyplusesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->id();
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
    }

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

Step 6: Create Route

In this step we will  add some route for laravel generate pdf:

Read Also :  Laravel Mailgun Integration Example

web.php

<?php

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

Route::get('disneyplus', [DisneyplusController::class,'create'])->name('disneyplus.create');
Route::post('disneyplus', [DisneyplusController::class,'store'])->name('disneyplus.store');

Route::get('disneyplus/list', [DisneyplusController::class,'index'])->name('disneyplus.index');
Route::get('/downloadPDF/{id}',[DisneyplusController::class,'downloadPDF'])->name('downloadPDF');

I hope you understand of laravel generate dynamic pdf from html and it can help you…