Skip to content

How to use mPDF In Yiiframework 2

Last updated on December 21, 2022

Hello there, Today I would like to show you how to integrate the 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 it in two ways – using composer or you can install it 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 download the 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 to 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 the array

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

How to use – Create PDF Using mPDF

Below is a simple example – you just need to import mPDF by using use mPDF;

And now you can create the object of mPDF. using the generated object you call all of the mPDF methods.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments