For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Generate PDF in CodeIgniter 4

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		app\Controllers\Generate.php
Library: 	Pdf.php		        app\Libraries\Pdf.php
View:		pdf_view.php            app\Views\pdf_view.php

app/Config/Routes.php

$routes->add('Generate/generate_pdf', 'Generate::generate_pdf');

app/Libraries/Pdf.php

<?php 
namespace App\Libraries;

use Dompdf\Dompdf;

class Pdf extends Dompdf {
	
	public function __construct() {
		parent::__construct();
	}
	
}

app/Controllers/Generate.php

<?php 
namespace App\Controllers;

use App\Controllers\BaseController;
use App\Libraries\Pdf;
use Dompdf\Dompdf;

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));	
	}
}

app/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