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. Copy and Paste the following lines in app/Config/Routes.php
$routes->add('Generate/generate_pdf', 'Generate::generate_pdf');
2. Create a controller file Pdf.php in the app/Libraries/ directory.
<?php namespace AppLibraries; use DompdfDompdf; class Pdf extends Dompdf { public function __construct() { parent::__construct(); } }
3. Create a controller file Generate.php in the app/Controllers/ directory.
<?php namespace AppControllers; use AppControllersBaseController; use AppLibrariesPdf; use DompdfDompdf; class Generate extends BaseController { public function __construct() { $this->parser = service('renderer'); } public function generate_pdf() { $dompdf = new Dompdf(); // Get Ouput from View $html = $this->parser->render('pdf_view'); // 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 the app/Views/ directory.
<!DOCTYPE html> <html> <body> <h1>My PDF Heading</h1> <p>My PDF paragraph.</p> </body> </html>