CodeIgniter 4 PDF Generate Tutorial

Share this Article
Reading Time: 9 minutes
38 Views

Most of the developers get stuck while converting HTML data into a PDF document. dompdf is the library which converts HTML to PDF.

Inside this article we will see how to generate a PDF of tabular data. As we are in session of CodeIgniter 4, so will cover about each steps of CodeIgniter 4 PDF Generate and few methods of dompdf library. This article will be in very simple steps.

We will include the concept of accessing data from database, render to HTML page and then download that HTML data into PDF format.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.

Now, we need to download and setup DomPDF library to CodeIgniter 4 application.


Install & Configure DOMPdf to CodeIgnter 4

To install DOMPdf in application, we will use composer. Back to the terminal, open application setup and run this command.

$ composer require dompdf/dompdf

Successfully, we have installed DOMPdf library to setup. Next, we need to do configuration to application.

Back to folder structure and open up the file /app/Config/Autoload.php, it’s a class file used to autoload the files.

Search for $psr4 array configuration inside file, we need to register service here.

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

Create Database, Table & Test Data in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE tbl_students (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s dump test data into it.

--
-- Dumping data for table `tbl_students`
--

INSERT INTO `tbl_students` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Sanjay Kumar', 'sanjay@gmail.com', '9632587410'),
(2, 'Vijay Kumar', 'vijay@gmail.com', '7418529630'),
(3, 'Rakesh Kumar', 'rakesh@gmail.com', '8527410963'),
(4, 'Kavita Singh', 'kavita@gmail.com', '8529647130'),
(5, 'Ashish Kumar', 'ashish@gmail.com', '7410852963'),
(6, 'Dhananjay Negi', 'dhananjay_negi@gmail.com', '7896541230'),
(7, 'Pradeep Goyal', 'pradeep_kumar@gmail.com', '1234567890'),
(8, 'Nilu Singh', 'nilu@gmail.com', '7026358941');

Run this query to created database, it will insert these dummy data into tbl_students table.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Create Route

To configure application routes, we need to open up the file Routes.php from /app/Config. This is the main routes config file where we will do all routes of application.

//.. Other routes

$routes->get("list-student", "Student::listStudent");
$routes->get("generate-pdf", "Student::generatePDF");

To remove /public/index.php from URL, you can find it’s complete resource here at this link.

Here, we have configured our application.


Application Controller Settings

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create Student.php inside the given folder. Open project into terminal and type this spark command.

$ php spark make:controller Student

Write the following code into /app/Controllers/Student.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Student extends BaseController
{
    public $db;
    
    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }
  	
    public function listStudent()
    {
        // Sending data to view file
        $data = $this->db->table("tbl_students")->get()->getResult();
        // Calling view file
        return view('list-student', [
            "students" => $data
        ]);
    }

    function generatePDF(){

        $dompdf = new \Dompdf\Dompdf(); 

        $data = $this->db->table("tbl_students")->get()->getResult();
        // Sending data to view file
        $dompdf->loadHtml(view('pdf/template-students', ["students" => $data]));
        // setting paper to portrait, also we have landscape
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        // Download pdf
        $dompdf->stream(); 
        // to give pdf file name
        // $dompdf->stream("myfile");

        return redirect()->to(base_url('list-student'));
    }
}

Let’s create view file.


View File Setup in Application

We need to create 2 view files –

  • To List all data
  • PDF HTML view

Let’s create it.

View files generally created inside /app/Views.

List User view file. File with the name of list-student.php

Code of /app/Views/list-student.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Generate PDF in Codeigniter 4</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>

<div class="container">
  <h2 style="text-align: center;">Generate PDF in Codeigniter 4 - Online Web Tutor</h2>
  <div class="panel panel-primary">
    <div class="panel-heading">
        Generate PDF in Codeigniter 4
        <a href="<?php echo base_url('generate-pdf') ?>" class="btn btn-info pull-right" style="margin-top:-7px">
        Download PDF
      </a>
    </div>
    <div class="panel-body">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                </tr>
            </thead>
            <tbody>
            <?php
                if(count($students) > 0){
                    foreach($students as $index => $student){
                        ?>
                        <tr>
                            <td><?= $student->id ?></td>
                            <td><?= $student->name ?></td>
                            <td><?= $student->email ?></td>
                            <td><?= $student->mobile ?></td>
                        </tr>
                        <?php
                    }
                }
            ?>
            </tbody>
        </table>
    </div>
  </div>
</div>

</body>
</html>

Create PDF template

Create a folder pdf at /app/Views and a file with name template-students.php inside that.

Open template-students.php and write this code.

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Codeigniter 4 PDF Generate Tutorial</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <style>
    table th {
          background: #0c1c60 !important;
          color: #fff !important;
          border: 1px solid #ddd !important;
          line-height:15px!important;
          text-align:center!important;
          vertical-align:middle!important;

      }
      table td{line-height:15px!important; text-align:center!important;}
  </style>
</head>

<body>
  <div class="container">

    <h2>Generate PDF in Codeigniter 4 - Online Web Tutor</h2>

    <table class="table table-striped">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
          <th>Mobile</th>
        </tr>
      </thead>
      <tbody>
        <?php
            if(count($students) > 0){
                foreach($students as $index => $student){
                    ?>
                    <tr>
                        <td><?= $student->id ?></td>
                        <td><?= $student->name ?></td>
                        <td><?= $student->email ?></td>
                        <td><?= $student->mobile ?></td>
                    </tr>
                    <?php
                }
            }
        ?>
      </tbody>
    </table>
  </div>
</body>

</html>

When we click on Download PDF button, above code will be complied and converted into PDF format. If you want more customization, then you can add or update HTML code.


Application Testing

Open project into terminal and start development server.

$ php spark serve

Run application by typing URL as – http://localhost:8080/list-student

we should get the output as

Learn about Generate Excel Report in CodeIgniter 4, Click here.

We hope this article helped you to learn about CodeIgniter 4 PDF Generate Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment