Generate HTML PDFs in CodeIgniter 4 with Dompdf

- Andrés Cruz

En español
Generate HTML PDFs in CodeIgniter 4 with Dompdf

The PDF by its acronym Portable Document Format, is a file format widely used to present and share digital documents in a safe and reliable way, they have the characteristic that they cannot be edited directly, as occurs with a text document, they can contain text and images and can be viewed on most devices and operating systems through programs like Adobe or as easily as web browsers.

At Codeigniter, although we don't have many framework-specific packages, we do have regular PHP packages; In this case, PDFs are not the exception and in principle we will use any package that is for PHP for CodeIgniter, used of course composer for this task.

What is Dompdf?

Dompdf is an HTML to PDF converter. At its core, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is a style-based renderer: it will download and read external style sheets, inline style tags, and the style attributes of individual HTML elements.

The following example shows how to use Dompdf to convert HTML and generate PDF with minimal configuration.

  • Specify the HTML content in the loadHtml() method of the Dompdf class.
  • Render HTML as PDF using the render() method.
  • Send the generated PDF to the browser using the stream() method.

Ideally, the PDF format is used to read the information in document form. The PDF file is indicated by the file extension .pdf and stands for Portable Document Format. A PDF document manifests information for eBooks, application forms, user manuals, and other documents.

In this tutorial, we assume that you are a Codeigniter developer and want to know how to create a PDF file from an HTML view template using the domPDF library.

Many novice developers get stuck when it comes to HTML to PDF conversion. Don't worry, we'll make it easy for you. By the end of this tutorial, you can generate a PDF file from the HTML layout with the DomPDF library.

 

In this entry, we are going to use Dompdf for its ease and time in the market, it is an ideal solution for when we want to work with PDFs in PHP; its use is simple:

We specify the HTML that we want to convert to pdf:

$dompdf->loadHTML('<h1>Hola Mundo</h1><br><p>Otro contenido</p>');

We indicate the size of the sheet:

$dompdf->setPaper('A4', 'portrait');

We generate the PDF:

$dompdf->render();

We start the download:

$dompdf->stream();

Install Dompdf in CodeIgniter:

As we were talking about, we will install Dompdf using composer:

composer require dompdf/dompdf

https://github.com/dompdf/dompdf

Create a PDF controller

With this, we are completely ready to use Doompdf in our application, starting, to create an instance:

$dompdf = new Dompdf();

And we generate the pdf and render:

$dompdf->loadHTML('<h1>Hola Mundo</h1><br><p>Otro contenido</p>');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream();

In the case of CodeIgniter 4, we have the view functions that the HTML returns to us in the controller; so we can use them perfectly instead of an HTML set from the controller:

$dompdf = new Dompdf();
$dompdf->loadHTML(view("dashboard/product/trace_pdf", $data));
$productModel = new ProductModel();
$product = $productModel->asObject()->find($productId);

In the case of CodeIgniter 4, we have the view functions that the HTML returns to us in the controller; so we can use them perfectly instead of an HTML set from the controller:

$dompdf = new Dompdf();
//$dompdf->loadHTML('<h1>Hola Mundo</h1><br><p>Otro contenido</p>');
$productModel = new ProductModel();
$product = $productModel->asObject()->find($productId);
$query = $productModel->asObject()->select("pc.*, u.email, puc.description, puc.direction")
            ->join('products_control as pc', 'pc.product_id = products.id')
            ->join('users as u', 'pc.user_id = u.id')
            ->join('products_users_control as puc', 'pc.id = puc.product_control_id');
$data = [
            'product' => $product,
            'trace' => $query->where('products.id', $productId)
                ->findAll()
];
$dompdf->loadHTML(
            view("dashboard/product/trace_pdf", $data)
);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream();

The view looks like this:

<style>
    * {
        color:blue
    }
</style>
<p>
    Ventas y compras de <?= $product->name ?>
</p>
<ul>
    <li>
        Precio <?= $product->price ?>
    </li>
    <li>
        Última Entrada <?= $product->entry ?>
    </li>
    <li>
        Última Salida <?= $product->exit ?>
    </li>
</ul>
<table>
    <thead>
        <tr>
            <th>
                ID
            </th>
            <th>
                Fecha
            </th>
            <th>
                Tipo
            </th>
            <th>
                Cantidad
            </th>
            <th>
                Usuario
            </th>
            <th>
                Descripción
            </th>
            <th>Dirección</th>
            <th>
                Precio
            </th>
            <th>
                Total
            </th>
        </tr>
    </thead>
    <tbody>
        <?php $total = 0 ?>
        <?php foreach ($trace as $key => $t) : ?>
            <tr>
                <td>
                    <?= $t->id ?>
                </td>
                <td>
                    <?= $t->created_at ?>
                </td>
                <td>
                    <?= $t->type ?>
                </td>
                <td>
                    <?= $t->count ?>
                </td>
                <td>
                    <?= $t->email ?>
                </td>
                <td>
                    <?= $t->description ?>
                </td>
                <td>
                    <?= $t->direction ?>
                </td>
                <td>
                    <?= $product->price ?>
                </td>
                <td>
                    <?php $total += $product->price * $t->count ?>
                    <?= $product->price * $t->count ?>
                </td>
            </tr>
        <?php endforeach ?>
        <tr>
            <td colspan="8">Total</td>
            <td><?= $total ?></td>
        </tr>
    </tbody>
</table>

And that's it, the important thing here is that we can easily extend the framework with any PHP package using composer, which is the recommended way when we install CodeIgniter 4.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.