How to Dynamically Generate PDF from HTML in Codeigniter 4

In this Codeigniter tutorial, we will learn how to easily generate PDF documents from an HTML page. After going through this article you will be able to export the PDF files from HTML in the Codeigniter application.

We will be using the DomPDF package to convert HTML to PDF in PHP Codeigniter application. This post will help to write effective PHP code to generate dynamic PDF files from HTML pages.

This tutorial will explain how to generate PDF from HTML using the DomPDF package. We will walk through each and every detail regarding the setting up of the DomPDF library in the Codeigniter application.

How to Generate Dynamic PDF File from HTML in Codeigniter 4

  • Step 1) Create New Codeigniter Project
  • Step 2) Configure the Database connection
  • Step 3) Installation of DomPDF package
  • Step 4) Setup Route
  • Step 5) Setup the Controller File
  • Step 6) Setup the View File
  • Step 7) Running the Application in Browser

 

Create New Codeigniter Project

Visit the official site to download the latest version of the Codeigniter application.

OR you can execute the composer command to create a new application. make sure you have composer installed and configured on your system.

composer create-project codeigniter4/appstarter

 

Configure the Database connection

To connect our application with the database, open the app/Config/Database.php file and update the credential.

public $default = [
	'DSN'      => '',
	'hostname' => 'localhost',
	'username' => 'my_username',
	'password' => 'my_password',
	'database' => 'my_database',
	'DBDriver' => 'MySQLi',
	'DBPrefix' => '',
	'pConnect' => false,
	'DBDebug'  => (ENVIRONMENT !== 'production'),
	'charset'  => 'utf8',
	'DBCollat' => 'utf8_general_ci',
	'swapPre'  => '',
	'encrypt'  => false,
	'compress' => false,
	'strictOn' => false,
	'failover' => [],
	'port'     => 3306,
];

 

Installation of DomPDF package

Install the DomPDF library by simply running the following composer command. It will add the DomPDF package into Codeigniter app.

composer require dompdf/dompdf

After the installation is completed, open the app/Config/Autoload.php file, and update the $psr4 array. We are updating to add 'Dompdf' service as shown below.

public $psr4 = [
	APP_NAMESPACE => APPPATH, // For custom app namespace
	'Config'      => APPPATH . 'Config',
	'Dompdf'      => APPPATH . 'ThirdParty/dompdf/src',
];

 

Setup Route

Now, add a new route that will have some HTML stuff like tabular data to be consumed in the view file.

Open the app/Config/Routes.php file, and append the following Route into it.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */


$routes->setDefaultController('HTMLPdfController');
$routes->get('/html-to-pdf-demo', 'HTMLPdfController::index');

 

Setup the Controller File

Next, create a new controller template file under the app/Controllers/HTMLPdfController.php , then update with the following code.

<?php

namespace App\Controllers;
use CodeIgniter\Controller;

class HTMLPdfController extends Controller {

    public function index() 
	{
        return view('index');
    }    

    function convertHTMLToPdf(){
        $dompdf = new \Dompdf\Dompdf(); 
        $dompdf->loadHtml(view('index'));
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();
        $dompdf->stream();
    }    

} ?>

 

Setup the View File

Finally, go to the views folder then create an index.php file.

In this file, add a sample HTML table with a button on top to call the controller function and generate the PDF document.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 PDF Example - thecodemon.com</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
  <div class="container mt-5">

    <h2>Generate PDF in Codeigniter from View</h2>

    <div class="d-flex flex-row-reverse bd-highlight">
      <a href="<?php echo base_url('HTMLPdfController/convertHTMLToPdf') ?>" class="btn btn-primary">
        Download PDF
      </a>
    </div>

    <table class="table table-striped table-hover mt-4">
      <thead>
        <tr>
          <th>Name</th>
          <th>Profile</th>
          <th>City</th>
          <th>Date</th>
          <th>CTC</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Airi Satou</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>33</td>
          <td>2008/11/28</td>
          <td>$162,700</td>
        </tr>
        <tr>
          <td>Angelica Ramos</td>
          <td>Chief Executive Officer (CEO)</td>
          <td>London</td>
          <td>47</td>
          <td>2009/10/09</td>
          <td>$1,200,000</td>
        </tr>
        <tr>
          <td>Ashton Cox</td>
          <td>Junior Technical Author</td>
          <td>San Francisco</td>
          <td>66</td>
          <td>2009/01/12</td>
          <td>$86,000</td>
        </tr>
        <tr>
          <td>Bradley Greer</td>
          <td>Software Engineer</td>
          <td>London</td>
          <td>41</td>
          <td>2012/10/13</td>
          <td>$132,000</td>
        </tr>
        <tr>
          <td>Brenden Wagner</td>
          <td>Software Engineer</td>
          <td>San Francisco</td>
          <td>28</td>
          <td>2011/06/07</td>
          <td>$206,850</td>
        </tr>
        <tr>
          <td>Brielle Williamson</td>
          <td>Integration Specialist</td>
          <td>New York</td>
          <td>61</td>
          <td>2012/12/02</td>
          <td>$372,000</td>
        </tr>
        <tr>
          <td>Bruno Nash</td>
          <td>Software Engineer</td>
          <td>London</td>
          <td>38</td>
          <td>2011/05/03</td>
          <td>$163,500</td>
        </tr>
        <tr>
          <td>Caesar Vance</td>
          <td>Pre-Sales Support</td>
          <td>New York</td>
          <td>21</td>
          <td>2011/12/12</td>
          <td>$106,450</td>
        </tr>
        <tr>
          <td>Cara Stevens</td>
          <td>Sales Assistant</td>
          <td>New York</td>
          <td>46</td>
          <td>2011/12/06</td>
          <td>$145,600</td>
        </tr>
        <tr>
          <td>Cedric Kelly</td>
          <td>Senior Javascript Developer</td>
          <td>Edinburgh</td>
          <td>22</td>
          <td>2012/03/29</td>
          <td>$433,060</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

</html>

 

Running the Application in Browser

Finally, run the Codeigniter application in the browser by executing below command.

php spark serve

 

Now enter the below URL in the browser to open the application with an HTML table having a button to create PDF file.

http://localhost:8080/html-to-pdf-demo

 

Conclusion

We have completed our tutorial on using the DomPDF package to convert HTML content in the view into PDF file.

Leave a Reply

Your email address will not be published. Required fields are marked *