Last updated on November 23, 2022
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 the composer. So in this post, I would like to use CodeIgniter 3 and composer to install and load the mPDF library.
Here are the steps to generate PDF in the CodeIgniter 3 application with mPDF:
Step 1: Download and install CodeIgniter.
Step 2: Run the below composer command to download the mPDF library from your project folder. It will create a new folder called “vendor” and it will download the “mPDF” library into it.
$ composer require mpdf/mpdf
Here is the directory structure after installing mPDF
Step 3: Open application/config/config.php
file and set your vendor directory path
$config['composer_autoload'] = 'vendor/autoload.php';
Step 4: Use the mPDF library inside 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 inside in your view folder with the 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>
application/views/welcome_message.php
<p>The corresponding controller for this page is found at:</p>
application/controllers/Welcome.php
<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, and you should get similar output: