Create PDF Files Using mPDF In Yiiframework 2.0

mPDF is a PHP class Which is used to create a PDF files from the HTML content in yii2.0.

Install mPDF

Install mPDF Using Composer

To include the mPDF package into yii2.0 application folder, add the following code into ‘composer.json’ file and run the command ‘composer update’. Now you can see the mPDF packages in your application.

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

In command prompt

composer update

(Or)
You can add the mPDF package through the command line using below code. We don’t need to add code in composer.json. It will be added automatically When we use this method.

php composer.phar require mpdf/mpdf "dev-master"

Now got to ‘vendor/composer/autoload_classmap.php’ file, All the preload class will be set on this file.

Install mPDF Manually

First goto the mPDF library path ‘https://github.com/mpdf/mpdf’. Download the .zip file and unzip it into application ‘Vendor’ folder. Now change the file path as mpdf/mpdf/ and See the below image for file structure.

mPDF In Yii2.0

mPDF In Yii2.0


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

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

Note: Manual configuration will be automatically removed If you update the composer.json. Be careful on composer handling.

Create PDF Using mPDF

Now I will create a function called ‘createMPDF’ in sitecontroller.php and will make it as pdf file.

SiteController.php

...............
use app\models\ContactForm;
use mPDF;
class SiteController extends Controller
{
...............
	public function actionCreateMPDF(){
		$mpdf=new mPDF();
		$mpdf->WriteHTML($this->renderPartial('mpdf'));
        $mpdf->Output();
        exit;
		//return $this->renderPartial('mpdf');
	}
	public function actionSamplePdf() {
        $mpdf = new mPDF;
        $mpdf->WriteHTML('Sample Text');
        $mpdf->Output();
        exit;
    }
	public function actionForceDownloadPdf(){
		$mpdf=new mPDF();
		$mpdf->WriteHTML($this->renderPartial('mpdf'));
        $mpdf->Output('MyPDF.pdf', 'D');
        exit;
	}
...............
}
MPDF View

MPDF View