Saturday, 1 October 2016

How to create PDF in yii2 using mpdf library

mPDF is a class to generate PDF files from HTML with Unicode/UTF-8.In this post i will show you how to integrate mPDF in yii2 to genreate a pdf file from html templates.

Create PDF Using mPDF

Install mPDF Using Composer : Open your composer.json file and add a "mpdf/mpdf":"*" or you can add it directly using php composer.phar require mpdf/mpdf "dev-master" running in your console this command will add it automatically in composer.json file.

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

Next thing you need to do is update the composer using command:

composer update

Usage: you can directly import the library class using use mPDF; in your controller class and then crate object for mPDF. using generated object you call all of mPDF methods.

namespace app\controllers;
use mPDF;
class PdfController extends \yii\web\Controller
   // show pdf in browser                        
   public function actionIndex(){
        $mpdf=new mPDF();
    // for download it directly     
    public function actionDownloadPdf(){
        $mpdf=new mPDF();
        $mpdf->Output('nameofpdf.pdf', 'D');

This is just a example of creating a pdf of template but for advanced usage you can read the documentation of mPDF library and read the functions like creating table layout , css styling your pdf , header and footer.I hope you like the post and please comment for any kind of help and suggestions.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts