About Lesson
For generating PDF files in CodeIgniter, we use an external library dompdf. By using composer you can download this library into your project.
You need to run the following command in your project’s root directory.
Example:
composer require dompdf/dompdf
1. Add the following lines in config/config.php
$config['composer_autoload'] = FALSE; // to $config['composer_autoload'] = TRUE;
2. Create a Pdf.php file in applications/libraries/ directory
<?php use DompdfDompdf; class Pdf extends Dompdf { public function __construct() { parent::__construct(); } }
3. Create a controller file Generate.php in the applications/controllers/ directory.
<?php use DompdfDompdf; 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)); } }
4. Create a pdf_view.php file in applications/views/ directory
<!DOCTYPE html> <html> <body> <h1>My PDF Heading</h1> <p>My PDF paragraph.</p> </body> </html>