Posted by Arjun on Saturday 7th November 2015

How to use mPDF In Yiiframework 2

How to Yii2 mpdf

Hello there, Today I would like to show you how to integrate mPDF library with Yii framework 2.First, let me give you some basic information about mPDF. mPDF is a PHP Class by using this we can easily generate PDF files from HTML templates so you can style your HTML template as you wish. Here are the simple steps to use mPDF with the YII2 framework.

You can install in tow way – using composer or you can install manually.

Install mPDF Using Composer

Require this package in your composer.json by adding "mpdf/mpdf":"*" or you can directly run php composer.phar require mpdf/mpdf "dev-master" or composer require mpdf/mpdf "dev-master" it will update your composer.json and downloads mPDF library.

"require": {
      "php": ">=5.4.0",
      "yiisoft/yii2": "*",
      "yiisoft/yii2-bootstrap": "*",
      "yiisoft/yii2-swiftmailer": "*",
      "mpdf/mpdf":"*"
  },

Next, update Composer from the Terminal

$ composer update

Install mPDF Manually

Download mPDF from : http://www.mpdf1.com/mpdf/index.php and Extract it to your vendor/ folder of your yii2 application. Now rename and change the file path as mpdf/mpdf/ and See the below image for file structure.

 How to use mPDF In Yiiframework 2

Now go to vendor/composer/autoload_namespaces.php file and add the below line to array

 'mPDF' => array($vendorDir . '/mpdf/mpdf'), 

How to use – Create PDF Using mPDF

Below is simple example – you just need to import mPDF by using use mPDF; and the crate object for mPDF. using generated object you call all of mPDF methods.

<?php
 
namespace app\controllers;
use mPDF;
 
class MpdfController extends \yii\web\Controller
{
		
   // show in browser						
   public function actionIndex(){
		$mpdf=new mPDF();
		$mpdf->WriteHTML($this->renderPartial('mpdf_view'));
        $mpdf->Output();
        exit;
	}
 
	// download 	
	public function actionForceDownloadPdf(){
		$mpdf=new mPDF();
		$mpdf->WriteHTML($this->renderPartial('mpdf_view'));
        $mpdf->Output('MyPDF.pdf', 'D');
        exit;
	}
}

Download