Skip to content

Codeigniter 4 Generate PDF using Mpdf

Last updated on November 17, 2022

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">

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

<body>
    <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>
        </div>
    </div>
</body>

</html>

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

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function index()
	{
		$mpdf = new \Mpdf\Mpdf();
		$html = view('html_to_pdf',[]);
		$mpdf->WriteHTML($html);
		$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:

http://localhost:8080
0 0 votes
Article Rating
Subscribe
Notify of
guest

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments