CodeIgniter 4

Codeigniter 4 Generate PDF using Mpdf

In this CodeIgniter 4 tutorial, we gonna convert HTML to pdf in CodeIgniter using Mpdf.

Below are the steps to generate PDF in the CodeIgniter 4 application with the mPDF library:

Step 1: Generate your CodeIgniter application using composer.

$ composer create-project codeigniter4/appstarter ci4-mpdf

Step 2: Test the application, change the directory to the project folder, and start the development server using spark.

$ cd ci4-mpdf
$ php spark serve

Now you should be able to access the application at http://localhost:8080/

Step 3: Now install the mPDF library using composer, as shown below.

$ composer require mpdf/mpdf

Step 4: Create a view file called app\Views\html_to_pdf.php in your view folder with the below sample HTML.

<!DOCTYPE html>
<html lang="en">

    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>

    <div id="container">
        <h1>Welcome to CodeIgniter!</h1>
        <div id="body">
            <p>The page you are looking at is being generated dynamically by CodeIgniter.</p>


Step 5: Let’s use the mPDF library inside your controller and convert the previous view file into a PDF file.


namespace App\Controllers;

class Home extends BaseController
	public function index()
		$mpdf = new \Mpdf\Mpdf();
		$html = view('html_to_pdf',[]);
		$this->response->setHeader('Content-Type', 'application/pdf');
		$mpdf->Output('arjun.pdf','I'); // opens in browser
		//$mpdf->Output('arjun.pdf','D'); // it downloads the file into the user system, with give name
		//return view('welcome_message');

Step 6: Start and test the application

Run the following command to start the application:

$ php spark serve

Enter the following URL in the browser to convert the HTML into PDF in Codeigniter 4 application:


By Praveen Anaparthi

11+ years of IT industry experience holding a wide range of skill sets and roles with significant work on PHP, Node.js, Python, Ruby, Docker, React.js, Microsoft Azure, Azure DevOps, Windows PowerShell, Shell script, Jenkins, MongoDB, SQL, MySQL, Apache, Nginx. etc. It is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

4 replies on “Codeigniter 4 Generate PDF using Mpdf”

Leave a Reply

Your email address will not be published.