Overview
In this example, I am going to show you how to generate PDF using the CodeIgniter framework PHP.
For generating PDF file in CodeIgniter, we use an external library dompdf. By using composer you can download this library into your project.
You need to run following command in your project's root directory.
Example:
composer require dompdf/dompdf
Here, we are using 3 files for generating PDF file:
Controller: Generate.php application\controllers\Generate.php
Library: Pdf.php application\libraries\Pdf.php
View: pdf_view.php application\views\pdf_view.php
application/config/config.php
$config['composer_autoload'] = FALSE;
// to
$config['composer_autoload'] = TRUE;
application/libraries/Pdf.php
<?php
use Dompdf\Dompdf;
class Pdf extends Dompdf {
public function __construct() {
parent::__construct();
}
}
application/controllers/Generate.php
<?php
use Dompdf\Dompdf;
class Generate extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library("pdf");
}
public function generate_pdf() {
// Pass view
$this->load->view('pdf_view');
// Get Ouput from View
$html = $this->output->get_output();
// Load $html in dompdf
$this->pdf->loadHtml($html);
// set page size and orientation
$this->pdf->setPaper('A4', 'portrait');
// generate pdf
$this->pdf->render();
// download or view pdf
$this->pdf->stream("file.pdf", array("Attachment"=> 1));
}
}
application/views/pdf_view.php
<!DOCTYPE html>
<html>
<body>
<h1>My PDF Heading</h1>
<p>My PDF paragraph.</p>
</body>
</html>
How to run?
Open your browser and refer following link:
http://localhost/yourproject/Generate/generate_pdf