How to Create PDF using DOMPDF in Codeigniter

In this topics, we will discus about how to create PDF using DOMPDF with Codeigniter Framework.

We are going to use a third-party library called Dompdf that enables us to create PDFs and save them to the server or directly display them.

Step 1: Create Librarie (application/libraries/Dompdf_gen.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dompdf_gen {
    public function __construct() {
        require_once APPPATH.'third_party/dompdf/dompdf_config.inc.php';
        $pdf = new DOMPDF();
        $CI =& get_instance();
        $CI->dompdf = $pdf;
    }
}

Step 2: Call Librarie in Controller

public function __construct() {
    parent::__construct ();
    $this->load->library('dompdf_gen');
}

Step 3: Controller Function Code

$pdfname = 'scheduling_'.date('YmdHis').".pdf";
  
$html = '
<style>
    table {
      display: table; border-collapse: collapse;
    }
    .pricedetail tr td
    {
        font-family:Verdana;
        font-size: 10px;
    }
    .pricedetail tr th
    {
        font-family:Verdana;
        font-size: 10px;
    }
</style>
<table border="1" width="100%" class="pricedetail">
    <tr> 
        <th>#</th>
        <th>Monday</th>
        <th>Tuesday</th>
        <th>Wednesday</th>
        <th>Thursday</th>
        <th>Friday</th>
    </tr>
</table>';
           
$this->dompdf->load_html($html);
$this->dompdf->render();
$output = $this->dompdf->output();
file_put_contents('public/pdf/'.$pdfname.'', $output);

Leave a Reply

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