CodeIgniter 4 PDF Generate Tutorial

Share this Article

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 (
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)

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', '', '9632587410'),
(2, 'Vijay Kumar', '', '7418529630'),
(3, 'Rakesh Kumar', '', '8527410963'),
(4, 'Kavita Singh', '', '8529647130'),
(5, 'Ashish Kumar', '', '7410852963'),
(6, 'Dhananjay Negi', '', '7896541230'),
(7, 'Pradeep Goyal', '', '1234567890'),
(8, 'Nilu Singh', '', '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.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


namespace App\Controllers;

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('list-student', ["students" => $data]));
        // setting paper to portrait, also we have landscape
        $dompdf->setPaper('A4', 'portrait');
        // Download pdf
        // 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 view file. View file for List Student. View files generally created inside /app/Views.

Let’s create it.

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

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

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

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Codeigniter 4 PDF Generate Tutorial - Online Web Tutor</title>
  <link rel="stylesheet" href="">

  <div class="container">

    <h2>Generate PDF in Codeigniter 4</h2>

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

    <table class="table table-striped">
            if(count($students) > 0){
                foreach($students as $index => $student){
                        <td><?= $student->id ?></td>
                        <td><?= $student->name ?></td>
                        <td><?= $student->email ?></td>
                        <td><?= $student->mobile ?></td>


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