Generating PDF from HTML In CodeIgniter 4

Generating PDF from HTML In CodeIgniter 4

Avatar photoPosted by

Good day to you and welcome to this blog, today I will be showing you how to generate PDF from HTML in CodeIgniter 4. PDF has been one of the most commonly used document format today. Most of the web apps has a functionality that generate a PDF for invoice. receipts, reports and others. By reading this blog you will be able learn how to generate a PDF file and add it as a feature in your future projects. Before we proceed, let’s have a little bit of explainers.

What is PDF? It stands for Portable Document Format. It is a file format developed by Adobe to present or display documents in a manner independent of application software, hardware and operating systems.

We will be using CodeIgniter 4 on this tutorial. CodeIgniter is one of the most powerful PHP frameworks. It is an open-source web framework that is used for rapid web development. It is popular for its exceptional performance, small footprint, requires nearly zero configuration, thorough documentation and many more. If you want to learn more about CodeIgniter just visit their documentation here.

Step 1: Install CodeIgniter 4

For us to install CodeIgniter 4 we can install via composer or directly download CodeIgniter 4 here:

Install via composer:

composer create-project codeigniter4/appstarter ci-4-pdf

Step 2: Change CodeIgniter Environment

The default environment of CodeIgniter is production, it is a safety feature to add security in case settings are messed up when it goes live. For us to change the environment we will rename or copy the file env to .env. Once it is renamed, open the file and uncomment and change the CI_ENVIRONMENT value from production to development.

.env

CI_ENVIRONMENT = development

Step 3: Install DOMPDF Package

We will then install this package dompdf/dompdf, this package will be used in converting HTML into PDF. Run this comman to install the package:

composer require dompdf/dompdf

Step 4: Create A View

The Views are the codes that what the user see and the code that the user can interact.

After installing the package, we will now create the view file that we will then convert to pdf. Create a file name resume.php in app/Views/ directory and add these line of codes:

app/Views/resume.php

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Resume</title>
</head>
<body>
    <div style="margin: 0 auto;display: block;width: 500px;">
        <table width="100%" border="1">
            <tr>
                <td colspan="2">
                    <img src="<?= $imageSrc ?>" style="width:200px;"> 
                </td>
            </tr>
            <tr>
                <td>Name:</td>
                <td><?= $name ?></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><?= $address ?></td>
            </tr>
            <tr>
                <td>Mobile Number:</td>
                <td><?= $mobileNumber ?></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><?= $email ?></td>
            </tr>
        </table>
    </div>
</body>
</html>

Before proceeding to the next step, make sure you have an image file in the /public directory since we will be adding an image when we generate the PDF file. Here is my sample image used that is saved on /public/img/profile.png :

Generating PDF from HTML In CodeIgniter 4

Step 5: Create A Controller

A Controller is the one responsible for receiving Request and returning Response. We will now create our controller, run this command to create a controller:

php spark make:controller PdfGenerator

After creating a controller add this method:

app/Controllers/PdfGenerator

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use Dompdf\Dompdf;

class PdfGenerator extends BaseController
{
    public function index()
    {
        $dompdf = new Dompdf();
        $data = [
            'imageSrc'    => $this->imageToBase64(ROOTPATH . '/public/img/profile.png'),
            'name'         => 'John Doe',
            'address'      => 'USA',
            'mobileNumber' => '000000000',
            'email'        => 'john.doe@email.com'
        ];
        $html = view('resume', $data);
        $dompdf->loadHtml($html);
        $dompdf->render();
        $dompdf->stream('resume.pdf', [ 'Attachment' => false ]);
    }

    private function imageToBase64($path) {
        $path = $path;
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        return $base64;
    }

}

Step 6 : Run the Application

After finishing the steps above, you can now run your application by executing the code below:

php spark serve

After successfully running your app, open this URL in your browser:

http://localhost:8080/pdfgenerator

Screenshots:

Final Output

Generating PDF from HTML In CodeIgniter 4