Home | About | View All Posts

26 Apr 2022

How to use or install mpdf manually in Yii2 framework

As we know mPDF is a poplular PHP library. We can generate PDF files from UTF-8 encoded HTML using this PHP library. It is mainly based on FPDF and HTML2FPDF. It can be installed by automatically using composer and also manually(not recommended officially).

How to install mPdf in Yii2 framework manually -
The mPdf version 7 does not advice for manual installation without composer so it is discouraged and not officially supported. The new mPdf uses many dependencies - libraries and classes. You need to install those dependencies also manually in the Yii2 framework. Please visit at "How to create PDF file in Yii2 using mpdf" for automatic installation using composer.

You can find library dependencies in the "require" array entry in the root composer.json file as following -
    ------------
    ------------
    },
	"require": {
		"php": "^5.6 || ^7.0 || ~8.0.0 || ~8.1.0",
		"ext-gd": "*",
		"ext-mbstring": "*",
		"myclabs/deep-copy": "^1.7",
		"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
		"php-http/message-factory": "^1.0",
		"psr/http-message": "^1.0",
		"psr/log": "^1.0 || ^2.0",
		"setasign/fpdi": "^2.1"
	},
	"require-dev": {
		"mockery/mockery": "^1.3.0",
        --------------
        --------------
Installing mPdf dependencies -
We need to install two require dependencies before mPdf library embed - "psr/log" and "setasign/fpdi". Other dependencies("myclabs/deep-copy", "paragonie/random_compat" etc.) are installed automatically in vendeor folder when you install the Yii2 advance applicaiton package.

  1. Installing "psr/log" -
    Navigate at the Yii2 project folder in command window and enter the following command ('yii2mpdf' is my yii2 project folder)-
       
    C:\xampp\htdocs\yii2mpdf>composer require psr/log
    
    You will get the error - "Interface 'Psr\Log\LoggerAwareInterface' not found" in the absence of "psr/log" package install directory in vendor folder of the Yii2 framwork.

  2. Installing "setasign/fpdi" -
    Navigate at the Yii2 project folder in command window and enter the following command ('yii2mpdf' is my yii2 project folder)-
       
    C:\xampp\htdocs\yii2mpdf>composer require setasign/fpdi
    
    You will get the error - "Trait 'setasign\Fpdi\FpdiTrait' not found" in the absence of "setasign/fpdi" package install directory in vendor folder of the Yii2 framwork.
Installing mPdf library manually -
Please visit at the url - "https://github.com/mpdf/mpdf for downloading the mPDF library files. You can download the mPDF library at this page by clicking at the "Code" button which shows the download link for the mPDF library zip like following screenshot -

mPDF lirary files zip download

Now navigate at the vendor folder in the Yii2 project(yii2mpdf is the my project folder name) and create a new folder "mpdf". Create another folder named as "mpdf" in this folder and copy all the files and folder of the downloaded mPDF library. You can observe the path and folders and files in the screenshot below -



Now it is time to inform to the Yii2 framework for newly added mPDF library files and folder. We will add the TWO new entries for mPDF into the autoload static file of the composer application. Below is the file path in my Yii2 project(yii2mpdf) -

File path - C:\xampp\htdocs\yii2mpdf\vendor\composer\autoload_static.php

We will place following first new entry for mPDF "LengthsPsr4" into "$prefixLengthsPsr4" array -
        ///////////////////ADDED FOR MPDF LIBRARY - STARTS//////////////////
        'M' => 
        array (
            'Mpdf\\' => 5,
        ),
        ///////////////////ADDED FOR MPDF LIBRARY - ENDS//////////////////
The following code shows the new entry in the "$prefixLengthsPsr4" array -
    public static $prefixLengthsPsr4 = array (
    ------------
    -------
    ----------------
    'P' => 
        array (
            'Psr\\Log\\' => 8,
            'Psr\\Http\\Message\\' => 17,
            'Psr\\EventDispatcher\\' => 20,
            'Psr\\Container\\' => 14,
            'Prophecy\\' => 9,
        ),
        ///////////////////ADDED FOR MPDF LIBRARY - STARTS//////////////////
        'M' => 
        array (
            'Mpdf\\' => 5,
        ),
        ///////////////////ADDED FOR MPDF LIBRARY - ENDS//////////////////
        'G' => 
        array (
            'GuzzleHttp\\Psr7\\' => 16,
        ),
        ------------------
        -----------------
        ------------------
        )
    
We will place following second new entry for mPDF "DirsPsr4" into "$prefixDirsPsr4" array -
        ///////////////////ADDED FOR MPDF LIBRARY - STARTS//////////////////
        'Mpdf\\' => 
        array (
            0 => __DIR__ . '/..' . '/mpdf/mpdf/src',
        ),
         ///////////////////ADDED FOR MPDF LIBRARY - EMDS//////////////////
The following code shows the new entry in the "$prefixLengthsPsr4" array -
    public static $prefixDirsPsr4 = array (
    
    ---------
    ------------
     'Psr\\EventDispatcher\\' => 
        array (
            0 => __DIR__ . '/..' . '/psr/event-dispatcher/src',
        ),
        'Psr\\Container\\' => 
        array (
            0 => __DIR__ . '/..' . '/psr/container/src',
        ),
        'Prophecy\\' => 
        array (
            0 => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy',
        ),
        ///////////////////ADDED FOR MPDF LIBRARY - STARTS//////////////////
        'Mpdf\\' => 
        array (
            0 => __DIR__ . '/..' . '/mpdf/mpdf/src',
        ),
         ///////////////////ADDED FOR MPDF LIBRARY - EMDS//////////////////
        'GuzzleHttp\\Psr7\\' => 
        array (
            0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
        ),
        -------------
        ------------------
        )
    

Writing action code in the controller for generating pdf file -
First, we will import or call the mpdf library into a controller by using the code "use Mpdf\Mpdf;". Here for demo purpose, we will use the SiteController controller. You can create or use own controller as per your requirement.

Controller file path - C:\xampp\htdocs\yii2mpdf\frontend\controllers\SiteController.php
namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

use Mpdf\Mpdf; //Importing the mpdf library

class SiteController extends Controller {
Now, we will write the action code in the above controller class for generating the pdf file using the mpdf library. We need to create an object for mPDF. The object will be used for calling the mpdf method to show or access the html content into a view file. Following are the action function code -
// importing or calling the mPDF library into a controller
use Mpdf\Mpdf;


public function actionTestPdf(){
 $mpdf=new mPDF();
 $mpdf->WriteHTML($this->renderPartial('test_pdf_content'));
 $mpdf->Output();
 exit;
 }
 
You can check in detail for the function renderPartial() (used in the above code) at View rendering process in yii2 framework

Writing pdf content in a view file for passing it into controller -
We will create new php file for showing the html content in the pdf format. Below is the file path for the html content -
View file path - C:\xampp\htdocs\yii2mpdf\frontend\views\site\pdf_content.php

This is sample html content for showing it in the generated pdf file. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Accessing the pdf file -
We can access the html content of the above view file in pdf format using following action url - "index.php?r=site/test-pdf"
Click here to view the pdf file as live demo.

If you prefer to install mPDF using composer - please visit and check it at "How to create PDF file in Yii2 using mpdf"
Tags :
Aashutosh Kumar Yadav

By Aashutosh Kumar Yadav

He is a PHP-based UI/Web designer and developer by profession and very interested in technical writing and blogging. He has been writing technical content for about 10 years and has proficient in practical knowledge and technical writing.
@www.infotokri.in

0 comments:

Post a Comment