Friday 15 June 2018

Laravel - How to Generate Dynamic PDF from HTML using DomPDF



Making of Dynamic PDF is required feature of any commercial web application, so here we have publish this post in which we have describe how to create dynamic pdf file in Laravel by using DomPDF library. Suppose we have working on any enterprise level web application by using Laravel then at that time we want to required to make output of our application in PDF report format from dynamic Mysql database. From this post we have make simple tutorial in which we have describe how to can we generate dynamic PDF file in step by step process which better understading to beginner laravel programmer.

In this tutorial we have use laravel-dompdf package for generate dynamic pdf file and by using this package we can also download pdf file in our local computer also. Here we have use mysql customer table, in which we have already inserted some data for create dynamic pdf file from that data in tabular format. For display data in proper in table in pdf file we have also add some inline css in html table code, because we have make pdf file from html by using dompdf package in Laravel.







Step 1 - Download Laravel Dompdf Package


For create PDF file in Laravel first we want to download laravel-dompdf package. For this first we want to write following command in command prompt terminal.


composer require barryvdh/laravel-dompdf


Download this packege we have to register this package into Laravel working environment, for this we have to open config/app.php file and add service provider and aliase details.


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

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


Step 2 - Create Controller


After this we have to create controller in our Laravel application by using composer command. This controller will handle http requrest to convert html code to PDF file.


php artisan make:controller DynamicPDFController


This command will make controller in app/Http/Controllers folder with name like DynamicPDFController.php. In this controller first we have to make index() method for fetch data from database and here for fetch data we have to get_customer_data() method and after this in index() method we have send data to view file. For convert HTML data to PDF we have make another method pdf() by using this method it will convert html code to PDF file. For html data here we have use convert_customer_data_to_html() method. Below you can find complete controller source code below.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use PDF;

class DynamicPDFController extends Controller
{
    function index()
    {
     $customer_data = $this->get_customer_data();
     return view('dynamic_pdf')->with('customer_data', $customer_data);
    }

    function get_customer_data()
    {
     $customer_data = DB::table('tbl_customer')
         ->limit(10)
         ->get();
     return $customer_data;
    }

    function pdf()
    {
     $pdf = \App::make('dompdf.wrapper');
     $pdf->loadHTML($this->convert_customer_data_to_html());
     return $pdf->stream();
    }

    function convert_customer_data_to_html()
    {
     $customer_data = $this->get_customer_data();
     $output = '
     <h3 align="center">Customer Data</h3>
     <table width="100%" style="border-collapse: collapse; border: 0px;">
      <tr>
    <th style="border: 1px solid; padding:12px;" width="20%">Name</th>
    <th style="border: 1px solid; padding:12px;" width="30%">Address</th>
    <th style="border: 1px solid; padding:12px;" width="15%">City</th>
    <th style="border: 1px solid; padding:12px;" width="15%">Postal Code</th>
    <th style="border: 1px solid; padding:12px;" width="20%">Country</th>
   </tr>
     ';  
     foreach($customer_data as $customer)
     {
      $output .= '
      <tr>
       <td style="border: 1px solid; padding:12px;">'.$customer->CustomerName.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Address.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->City.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->PostalCode.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Country.'</td>
      </tr>
      ';
     }
     $output .= '</table>';
     return $output;
    }
}


Step 3 - Create view file


After this we have make view file in resources/view/dynamic_pdf.blade.php. This file has received data from controller index() method and display dynamic data in html table format. After this we have make on button for convert this html data to pdf file. When we have click on this button then it has send request to pdf() method of controller which will convert html to PDF file by using dompdf package in laravel which we can see on web page.


<!DOCTYPE html>
<html>
 <head>
  <title>Laravel - How to Generate Dynamic PDF from HTML using DomPDF</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>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Laravel - How to Generate Dynamic PDF from HTML using DomPDF</h3><br />
   
   <div class="row">
    <div class="col-md-7" align="right">
     <h4>Customer Data</h4>
    </div>
    <div class="col-md-5" align="right">
     <a href="{{ url('dynamic_pdf/pdf') }}" class="btn btn-danger">Convert into PDF</a>
    </div>
   </div>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <thead>
      <tr>
       <th>Name</th>
       <th>Address</th>
       <th>City</th>
       <th>Postal Code</th>
       <th>Country</th>
      </tr>
     </thead>
     <tbody>
     @foreach($customer_data as $customer)
      <tr>
       <td>{{ $customer->CustomerName }}</td>
       <td>{{ $customer->Address }}</td>
       <td>{{ $customer->City }}</td>
       <td>{{ $customer->PostalCode }}</td>
       <td>{{ $customer->Country }}</td>
      </tr>
     @endforeach
     </tbody>
    </table>
   </div>
  </div>
 </body>
</html>


Step 4 - Add Route


This is last step for generate dynamic pdf file in laravel by using dompdf package and here we want to set route for index() and pdf() method of DynamicPDFController.php file. For this we have to go to app/Http/routes.php and write following code for set route in our laravel application.


Route::get('/dynamic_pdf', 'DynamicPDFController@index');

Route::get('/dynamic_pdf/pdf', 'DynamicPDFController@pdf');


So, this is complete step by step process for create PDF file in Laravel by using Dompdf package.

21 comments:

  1. Thanks for awesome tutorials , it's help me lot.
    Please i start with follow your tutorials but i need report header where i can set my company name and logo, and also footer where i want to show page_count, prepared_by, date.

    please how i implement it. for all individual report page in my laravel project.

    thanks in advanced.

    ReplyDelete
  2. please create a tutorials- Search data from database and show data in table view and then How generate pdf view file like your this tutorials.

    thanks

    ReplyDelete
  3. sir
    how to add scrollbar to pdf so that i can see full data.

    ReplyDelete
  4. This tutorial just saved my life
    Thanks a million

    ReplyDelete
  5. when i install composer require barryvdh/laravel-dompdf there's an error because required dompdf/dompdf ^0.8 and when i install dompdf/dompdf ^0.8 there's an error because phenx/php-font-lib: 0.5.* is required and i don't know how to put it any suggestion?

    ReplyDelete
  6. can u help me please
    +91 9678850892

    ReplyDelete
  7. Большое спасибо! Очень качественный урок!

    ReplyDelete
  8. Please i want to send it by email how ?

    ReplyDelete
  9. Images? How is working one with images?

    ReplyDelete
  10. sir how to change to landsape on this dompdf

    ReplyDelete
  11. Class dompdf.wrapper does not exist

    ReplyDelete
  12. Good one! Love reading this blog i have also tried PDFbeaver.com for this purpose.

    ReplyDelete
  13. is it possible data with more than 1 page can be converted into pdf????

    ReplyDelete
  14. urdu language not supported is there any trick to resolve it?

    ReplyDelete
  15. why you not add the complete source code which can be download and video and text have differece in video you did something and uder the text you mentioned is another thing what is this please send me complete zip file of this course

    ReplyDelete