Krajee
Thankful to Krajee! BUY A COFFEEor to get more out of us.
The yii2-mpdf extension is a Yii2 wrapper component for the mPDF library with enhancements. The mPDF library offers ability to generate PDF files from UTF-8 encoded HTML. This library is based on FPDF and HTML2FPDF, with a number of enhancements. The key features in the library are to be able to generate PDF files 'on-the-fly' from HTML content, handling different languages. See the list of features and/or examples for the library. The yii2-mpdf extension offers an easy way to integrate and use the mPDF library within your Yii application with subtle enhancements. The key features offerred with this release are:
  • Setup pdf component globally in your yii application configuration.

  • Setup mPDF properties or call mPDF methods easily using simple array configuration.

  • Enhances extension to setup your own custom CSS file for rendering the formatted HTML content.

  • Extension has a built-in version of bootstrap.css (v3.3.0 modified for mPDF) to be applied by default. This will allow you to generate PDF content from bootstrap markup HTML easily.

  • Offers easy way to prepend inline CSS in addition to your own CSS file.

  • Offers easy to use object oriented methods to render complex PDF.

  • Easy use of the extension like any Yii widget by using the render method with minimal configuration.

  • The extension uses the latest development version (v6.0beta) of the mPDF library. It uses the composer repository kartik-v/mpdf on packagist as a source for this latest version. mPDF 6.0 can utilise OpenType layout tables to display complex scripts. This release (v6.0) contains fonts (open source) to cover almost every imaginable script / language. Includes support for Arabic or Indic scripts (as well as Khmer, Lao, Myanmar etc.). It also is expected to improve the display of Thai, Vietnamese and Hebrew. It also includes additional fonts for Chinese, Japanese, and Korean.

  • Inbuilt integration with yii2-grid extension that allows you to export grid as PDF and even generate advanced PDF reports.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

The yii2-mpdf extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-mpdf via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-mpdf "dev-master"

or add:

"kartik-v/yii2-mpdf": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

The extension includes the \kartik\mpdf\Pdf Component class (which extends and builds upon the yii/base/Component class). It allows you to configure and setup the following properties:

  • mode: string, specifies the mPDF mode of the new document. If the mode is set by passing a country/language string, this may also set: available fonts, text justification, and directionality RTL. Defaults to Pdf::MODE_BLANK. Some common predefined settings have been made available in this extension:

    • Pdf::MODE_BLANK or empty string

    • Pdf::MODE_CORE or c

    • Pdf::MODE_UTF8 or utf-8

    • Pdf::MODE_ASIAN or +aCJK

    Refer the mPDF function manual for details.

  • format: string | array, the format can be specified either as a pre-defined page size, or as an array of width and height in millimetres. Defaults to Pdf::FORMAT_A4. Some common predefined settings have been made available in this extension:

    • Pdf::FORMAT_A3 or A3

    • Pdf::FORMAT_A4 or A4

    • Pdf::FORMAT_LETTER or Letter

    • Pdf::FORMAT_LEGAL or Legal

    • Pdf::FORMAT_FOLIO or Folio

    • Pdf::FORMAT_LEDGER or Ledger-L

    • Pdf::FORMAT_TABLOID or Tabloid

    Refer the mPDF function manual for details.

  • defaultFontSize: float, the default document font size in points (pt).

  • defaultFont: string, the default font-family for the new document. Uses default value set in defaultCSS unless codepage has been set to win-1252. If codepage = win-1252, the appropriate core Adobe font will be set i.e. Helvetica, Times, or Courier.

  • marginLeft: float, sets the page left margin for the new document. All values should be specified as LENGTH in millimetres. If you are creating a DOUBLE-SIDED document, the margin values specified will be used for ODD pages; left and right margins will be mirrored for EVEN pages.

  • marginRight: float, sets the page right margin for the new document. All values should be specified as LENGTH in millimetres. If you are creating a DOUBLE-SIDED document, the margin values specified will be used for ODD pages; left and right margins will be mirrored for EVEN pages.

  • marginTop: float, sets the page top margin for the new document (in millimetres).

  • marginBottom: float, sets the page bottom margin for the new document (in millimetres).

  • marginHeader: float, sets the page header margin for the new document (in millimetres).

  • marginFooter: float, sets the page footer margin for the new document (in millimetres).

  • orientation: float, sets the page orientation for the new document. Defaults to Pdf::ORIENT_PORTRAIT. The predefined settings that have been made available in this extension are:

    • Pdf::ORIENT_PORTRAIT or P

    • Pdf::ORIENT_LANDSCAPE or L

  • cssFile: string, the css file to prepend to the PDF for formatting/styling your pdf output. The extension by default includes a modified version of bootstrap v3.3.0 CSS file that can be parsed by mPDF. The cssFile can be set up as a Yii path alias format. The cssFile defaults to the following:

    @vendor/kartik-v/yii2-mpdf/assets/bootstrap.min.css
    
  • cssInline: string, additional inline css to append after the cssFile.

    Important

    You MUST NOT enclose the inline CSS within <style> tags.
  • content: string, the HTML content to be converted to PDF format.

    Important

    You must be careful when your html markup includes <body> or other <style> tags. Any <style> tag will be skipped (you must use cssInline property for this). If <body> tags are found, all html outside these tags are discarded, and the rest is parsed as content for the document. If no <body> tags are found, all html is parsed as content.
  • filename: string, the output PDF filename.

  • destination: string, the PDF output destination. Defaults to Pdf::DEST_BROWSER. The predefined settings that have been made available in this extension are:

    • Pdf::DEST_BROWSER or I: send the file inline to the browser. The name given by filename is used when one selects the "Save as" option on the link generating the PDF.

    • Pdf::DEST_DOWNLOAD or D: send to the browser and force a file download with the name given by filename.

    • Pdf::DEST_FILE or F: save to a local file with the name given by filename (may include a path).

    • Pdf::DEST_STRING or S: return the document as a string. The filename is ignored.

    Refer the mPDF output manual for details.

  • tempPath: string, the folder path for storing the temporary data generated by mpdf. If not set this defaults to Yii::$app->getAlias('@app/runtime/mpdf').

  • methods: array, the mPDF list of methods to be called in the sequence before rendering the content. Should be an associative array of $method => $params format, where:

    • $method: string, is the mPDF method / function name.

      Refer the mPDF functions overview for details.

    • $param: array, are the mPDF method parameters.

      Refer the mPDF functions overview for details.

      NOTE: You must pass all the method's parameters as a linear array, that can be used by PHP call_user_func_array. For example:

      'methods' => [
          'SetHeader' => ['Test Export']
          'SetFooter' => ['{PAGENO}']
      ]
      

      The above configuration will automatically run the mPDF methods in the sequence listed below:

      $mPDF->SetHeader('Test Export');
      $mPDF->SetFooter('{PAGENO}');
      
  • options: array, the mPDF configuration options entered as an associative array in $key => $value format, where:

    • $key: string, is the mPDF configuration property name.

    • $value: mixed, is is the mPDF configured property value.

    For example, you can set mPDF document properties as below:

    'options' => [
        'title' => 'PDF Document Title',
        'subject' => 'PDF Document Subject'
        'keywords' => 'krajee, grid, export, yii2-grid, pdf'
    ]
    

    The above configuration will automatically set the mPDF properties in the sequence listed below:

    $mPDF->title = 'PDF Document Title';
    $mPDF->subject = 'PDF Document Subject';
    $mPDF->keywords =  'krajee, grid, export, yii2-grid, pdf';
    

    The following options are set by default if you do not set anything in options.

    [
        'autoScriptToLang' => true,
        'ignore_invalid_utf8' => true,
        'tabSpaces' => 4
    ]
    

The \kartik\mpdf\Pdf component includes these public methods:

  • render: renders the PDF content - returns the mPDF Output as set in destination property. In most cases, you can directly use this method after the component initialization. Refer the usage section for details.

  • getApi: returns the mPDF object.

  • setApi: sets the mPDF object.

  • getCss: gets the CSS string to be prepended by merging content from the cssFile and cssInline.

  • configure: Configures mPDF library options. The following parameters are required for this method:

    • options: array, the mPDF configuration options entered as an associative array in $key => $value format, where:

      • $key: string, is the mPDF configuration property name.

      • $value: mixed, is is the mPDF configured property value.

  • execute: Executes mPDF library methods. The following parameters are required for this method:

    • methods: array, the mPDF list of methods to be called in the sequence before rendering the content. Should be an associative array of $method => $params format, where:

  • output: Generates a PDF output. The following parameters are required for this method:

    • content: string, the input HTML content

    • file: string, the name of the file. If not specified, the document will be sent to the browser inline (destination Pdf::DEST_BROWSER).

    • dest: string, he destination. Defaults to Pdf::DEST_BROWSER.

You can setup and use the component in various number of ways:
The component can be used straightforward in a manner similar to any widget to render your HTML content as PDF. For example, you can call the component simply like below in your controller action:
use kartik\mpdf\Pdf;

public function actionReport() {
    // get your HTML raw content without any layouts or scripts
    $content = $this->renderPartial('_reportView');
    
    // setup kartik\mpdf\Pdf component
    $pdf = new Pdf([
        // set to use core fonts only
        'mode' => Pdf::MODE_CORE, 
        // A4 paper format
        'format' => Pdf::FORMAT_A4, 
        // portrait orientation
        'orientation' => Pdf::ORIENT_PORTRAIT, 
        // stream to browser inline
        'destination' => Pdf::DEST_BROWSER, 
        // your html content input
        'content' => $content,  
        // format content from your own css file if needed or use the
        // enhanced bootstrap css built by Krajee for mPDF formatting 
        'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
        // any css to be embedded if required
        'cssInline' => '.kv-heading-1{font-size:18px}', 
         // set mPDF properties on the fly
        'options' => ['title' => 'Krajee Report Title'],
         // call mPDF methods on the fly
        'methods' => [ 
            'SetHeader'=>['Krajee Report Header'], 
            'SetFooter'=>['{PAGENO}'],
        ]
    ]);
    
    // return the pdf output as per the destination setting
    return $pdf->render(); 
}	
You can also setup the widget as a global component for use across your application with defaults preset. For example, setup the following in the components section of your Yii application configuration file:
use kartik\mpdf\Pdf;
// ...
'components' => [
    // setup Krajee Pdf component
    'pdf' => [
        'class' => Pdf::classname(),
        'format' => Pdf::FORMAT_A4,
        'orientation' => Pdf::ORIENT_PORTRAIT,
        'destination' => Pdf::DEST_BROWSER,
        // refer settings section for all configuration options
    ]
]

Once you have setup the component, you can refer it across your application easily:

$pdf = Yii::$app->pdf;
$pdf->content = $htmlContent;
return $pdf->render();
If you need to use the component for advanced PDF rendering or using various other mPDF manipulations, then you could directly use the mPDF api as shown below.
use kartik\mpdf\Pdf;
$pdf = Yii::$app->pdf; // or new Pdf();
$mpdf = $pdf->api; // fetches mpdf api
$mpdf->SetHeader('Kartik Header'); // call methods or set any properties
$mpdf->WriteHtml($content); // call mpdf write html
echo $mpdf->Output('filename', 'D'); // call the mpdf api output as needed
Demonstration of a live example of rendering PDF files from HTML on the fly. The button below on clicking, renders the Krajee.com privacy policy statement as a PDF file.
/**
 * THE VIEW BUTTON
 */
echo Html::a('<i class="fa far fa-hand-point-up"></i> Privacy Statement', ['/site/view-privacy'], [
    'class'=>'btn btn-danger', 
    'target'=>'_blank', 
    'data-toggle'=>'tooltip', 
    'title'=>'Will open the generated PDF file in a new window'
]);

/**
 * THE CONTROLLER ACTION
 */
use kartik\mpdf\Pdf;

// Privacy statement output demo
public function actionViewPrivacy() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
    $pdf = new Pdf([
        'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
        'destination' => Pdf::DEST_BROWSER,
        'content' => $this->renderPartial('privacy'),
        'options' => [
            // any mpdf options you wish to set
        ],
        'methods' => [
            'SetTitle' => 'Privacy Policy - Krajee.com',
            'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
            'SetHeader' => ['Krajee Privacy Policy||Generated On: ' . date("r")],
            'SetFooter' => ['|Page {PAGENO}|'],
            'SetAuthor' => 'Kartik Visweswaran',
            'SetCreator' => 'Kartik Visweswaran',
            'SetKeywords' => 'Krajee, Yii2, Export, PDF, MPDF, Output, Privacy, Policy, yii2-mpdf',
        ]
    ]);
    return $pdf->render();
}

yii2-mpdf is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017