Posted by Arjun on Wednesday 31st January 2018

Using mPDF with CodeIgniter 3

mpdf CodeIgniter 3

In my previous post, I wrote a tutorial on Generating a PDF in Codeigniter using mPDF and in that tutorial I covered mPDF library manual installation steps, without composer. So in this post, I would like to use CodeIgniter 3 and composer to install and to load mPDF library.

Using mPDF with CodeIgniter 3

Here are the steps to generate PDF in the CodeIgniter 3 application with mPDF:

Step 1: Download and install CodeIgniter.

Step 2: Run below composer command to download mPDF library from your project folder. It will create a new folder called "vendor" and it will download "mpdf" library into it.

$ composer require mpdf/mpdf

Here is my the directory structure after installing mpdf

Step 3: Open application/config/config.php file and set you vendor directory path

 $config['composer_autoload'] = 'vendor/autoload.php';

Step 4: Use mPDF library inside in your controller, here is the sample:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	public function index()
	{
		$mpdf = new \Mpdf\Mpdf();
		$html = $this->load->view('html_to_pdf',[],true);
		$mpdf->WriteHTML($html);
		$mpdf->Output(); // opens in browser
		//$mpdf->Output('arjun.pdf','D'); // it downloads the file into the user system, with give name
	}

}

Step 5: create a view called html_to_pdf.php file in side in your view folder with below 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>

		<p>If you would like to edit this page you'll find it located at:</p>
		<code>application/views/welcome_message.php</code>

		<p>The corresponding controller for this page is found at:</p>
		<code>application/controllers/Welcome.php</code>

		<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
	</div>

</div>

</body>
</html>

Step 6: That's it. Very quick and simple. Now access your CodeIgniter application, you should get similar output: