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.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...