generate pdf in codeigniter using mpdf

 

generate pdf in codeigniter using mpdf | How To Generate Pdf In Codeigniter 4 (ci4) Using MPDF Library

in this post/blog/article we will give you information about How to generate pdf in Codeigniter using mpdf Library – CodeWithTanveer. Hear we will give you detail about How to generate pdf in Codeigniter4 using MPDF Library – CodeWithTanveer And how to use it also give you demo for it if it is necessary.

Step:- 1


first of all i have install codeigniter4 application with Run Command using composer package manager.


composer create-project codeigniter4/appstarter


You can also manually download the Codeigniter application.


Step-2 


After install codeigniter4 application. ihave install mpdf library file for genrate pdf file with Run command using composer manager


   composer require mpdf/mpdf


  you can also download from github.


Step:- 3


Afetr install mpdf library file then this file/folder put in app/ThirdParty


Step:- 4


Configure Database Condition


in this step i have configure datbase Include your database name, username and password in app/Config/Database.php file and make the database connection to handle data dynamically.



    public $default = [
            'DSN'      => '',
            'hostname' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'demo',
            'DBDriver' => 'MySQLi',
            'DBPrefix' => '',
            'pConnect' => false,
            'DBDebug'  => (ENVIRONMENT !== 'production'),
            'charset'  => 'utf8',
            'DBCollat' => 'utf8_general_ci',
            'swapPre'  => '',
            'encrypt'  => false,
            'compress' => false,
            'strictOn' => false,
            'failover' => [],
            'port'     => 3306,
    ];



Step:- 5


Create the users table and insert some random data into it, these records will be used through pdf component in Codeigniter application.



    CREATE TABLE users (
        id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
        name varchar(100) NOT NULL COMMENT 'Name',
        email varchar(255) NOT NULL COMMENT 'Email Address',
        PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
    INSERT INTO `users` (`id`, `name`, `email`) VALUES
    (1, 'Tanveer Ansari', 'tanveeransari@gmail.com'),
    (2, 'Ajay Maurya', 'ajay@gmail.com'),
    (3, 'Salman', 'salman@gmail.com'),
    (4, 'John Doe LI', 'johnli@gmail.com'),
    (5, 'Paul Bettany Ku', 'paulku@gmail.com'),
    (6, 'Vanya Yadav', 'vanyayadav@gmail.com'),
    (7, 'Vikas Yadav', 'vikasayadav@gmail.com'),



Step:- 6


If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.



    # MAMPP
    public $default = [
      ...
        'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
      ...
    ]
    # XAMPP
    public $default = [
      ...
        'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
      ...
    ]


Step:- 7


Create Model

Model manifests the particular data and business logic in MVC architecture. It manages the data of the application.


So, we have first create a app/Models/UserModel.php file, thereafter place the following codes.


    namespace App\Models;
    use CodeIgniter\Model;
    class UserModel extends Model
    {
        protected $table = 'users';
        protected $primaryKey = 'id';
        protected $allowedFields = ['name', 'email'];

        public function userlist(){
          $querysql = "SELECT * FROM users";
          $query = $this->db->query($querysql);
          $data= $query->getResultArray();
          return $data;
      }
    }

 

    Step:- 8

    Setup autoload.php file in app/Config/Constants.php 

 
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'app/ThirdParty/vendor/autoload.php');


Step:- 9


Setting Up Controller

Create app/Controllers/UserController.php and insert the following code inside of it.


Import UserModel at the top section of the User controller, create the new UserModel instance. Make the query fetch the records from the database, load the records in the Codeigniter view.


   
namespace App\Controllers;
    use App\Models\UserModel;
    use CodeIgniter\Controller;
    use \Mpdf\Mpdf;
    class UserController extends Controller
    {
        public function createpdf() {
          $userModel = new UserModel();
          $mpdf = new Mpdf(['mode' => 'utf-8']);
          $data['details'] = $userModel->userlist();
          echo $html = view('user_view', $data);
          $mpdf->WriteHTML($html);
          $this->response->setHeader('Content-Type', 'application/pdf');
          $mpdf->Output('Userlist.pdf', 'I');
           
        }
   
    }


Step:-10

Define Routes

Create the route, It will be used to display the records in tabular form where we can implement pagination. Place the following code in app/Config/Routes.php.



  $routes->get('users', 'UserController::createpdf');


Step:- 11

Display Pdf

Here the compendium of code describes, we have to display the data using Bootstrap 4 Table with Pdf.

Create app/Views/user_view.php file and insert the following code in it.




      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Generate Pdf with codeigniter4 application using mpdf library - CodeWithTanveer</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
      </head>
      <body>
        <div class="container mt-5">
          <div class="mt-3">
            <table class="table table-bordered" style="width:100%;" id="">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Email</th>
                </tr>
              </thead>
              <tbody>
                <?php if($details): ?>
                <?php foreach($details as $list): ?>
                <tr>
                  <td><?php echo $list['id']; ?></td>
                  <td><?php echo $list['name']; ?></td>
                  <td><?php echo $list['email']; ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </body>
      </html>






0 Comments