Class kartik\mpdf\Pdf

Inheritancekartik\mpdf\Pdf » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version1.0

The Pdf class is a Yii2 component that allows to convert HTML content to portable document format (PDF). It allows configuration of how the PDF document is generated and how it should be delivered to the user. This component uses the Mpdf library and includes various additional enhancements specifically for the Yii2 framework.

The component can be used like a widget directly to render PDF as shown below:

use kartik\mpdf\Pdf;

// OPTION 1: widget like usage
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();

See also https://mpdf.github.io/.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$api \Mpdf\Mpdf the Mpdf object instance (readonly property accessed via getter getApi()) kartik\mpdf\Pdf
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$content string The HTML content to be converted to PDF kartik\mpdf\Pdf
$css array fetches the content of the CSS file if configured (readonly property accessed via getter getCss()) kartik\mpdf\Pdf
$cssFile array|string Css files to prepend to the PDF kartik\mpdf\Pdf
$cssInline string Additional inline css to append after the cssFile kartik\mpdf\Pdf
$defaultFont string Sets the default font-family for the new document. kartik\mpdf\Pdf
$defaultFontSize integer Sets the default document font size in points (pt) kartik\mpdf\Pdf
$destination string The output destination kartik\mpdf\Pdf
$filename string The output filename kartik\mpdf\Pdf
$format string|\kartik\mpdf\array, The format can be specified either as a pre-defined page size, or as an array of width and height in millimetres. kartik\mpdf\Pdf
$marginBottom float Sets the page bottom margin for the new document (in millimetres). kartik\mpdf\Pdf
$marginFooter float Sets the page footer margin for the new document (in millimetres). kartik\mpdf\Pdf
$marginHeader float Sets the page header margin for the new document (in millimetres). kartik\mpdf\Pdf
$marginLeft float Sets the page left margin for the new document. kartik\mpdf\Pdf
$marginRight float Sets the page right margin for the new document (in millimetres). kartik\mpdf\Pdf
$marginTop float Sets the page top margin for the new document (in millimetres). kartik\mpdf\Pdf
$methods array The Mpdf methods that will called in the sequence listed before rendering the content. kartik\mpdf\Pdf
$mode string Specifies the mode of the new document. kartik\mpdf\Pdf
$options array The Mpdf configuration options entered as $key => value pairs, where: - $key: string, is the configuration property name - $value: mixed, is the configured property value kartik\mpdf\Pdf
$orientation string Specifies the default page orientation of the new document. kartik\mpdf\Pdf
$pdfAttachments array list of file paths that should be attached to the generated PDF (readonly property accessed via getter getPdfAttachments()) kartik\mpdf\Pdf
$tempPath string The folder path for storing the temporary data generated by mpdf. kartik\mpdf\Pdf

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$_css string The css file content kartik\mpdf\Pdf
$_mpdf \Mpdf\Mpdf Api instance kartik\mpdf\Pdf
$_pdfAttachments array List of file paths that should be attached to the generated PDF kartik\mpdf\Pdf

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
addPdfAttachment() Adds a PDF attachment to the generated PDF kartik\mpdf\Pdf
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
execute() Calls the Mpdf method with parameters kartik\mpdf\Pdf
getApi() Validates and fetches the Mpdf API instance. kartik\mpdf\Pdf
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getCss() Fetches the content of the CSS file if supplied kartik\mpdf\Pdf
getPdfAttachments() Gets the list of currently attached PDF attachments. kartik\mpdf\Pdf
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. kartik\mpdf\Pdf
initTempPaths() Initialize folder paths to allow Mpdf to write temporary data. kartik\mpdf\Pdf
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
output() Generates a PDF output kartik\mpdf\Pdf
parseFormat() Parse the format automatically based on the orientation kartik\mpdf\Pdf
render() Renders and returns the PDF output. Uses the class level property settings. kartik\mpdf\Pdf
setApi() Sets the Mpdf API instance kartik\mpdf\Pdf
trigger() Triggers an event. yii\base\Component
writePdfAttachment() Appends the given attachment to the generated PDF kartik\mpdf\Pdf

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
DEST_BROWSER 'I' File output sent to browser inline kartik\mpdf\Pdf
DEST_DOWNLOAD 'D' File output sent for direct download kartik\mpdf\Pdf
DEST_FILE 'F' File output sent to a file kartik\mpdf\Pdf
DEST_STRING 'S' File output sent as a string kartik\mpdf\Pdf
FORMAT_A3 'A3' A3 page size format kartik\mpdf\Pdf
FORMAT_A4 'A4' A4 page size format kartik\mpdf\Pdf
FORMAT_FOLIO 'Folio' Folio page size format kartik\mpdf\Pdf
FORMAT_LEDGER 'Ledger-L' Ledger page size format kartik\mpdf\Pdf
FORMAT_LETTER 'Letter' Letter page size format kartik\mpdf\Pdf
FORMAT_TABLOID 'Tabloid' Tabloid page size format kartik\mpdf\Pdf
MODE_ASIAN '+aCJK' Asian fonts mode kartik\mpdf\Pdf
MODE_BLANK '' Blank default mode kartik\mpdf\Pdf
MODE_CORE 'c' Core fonts mode kartik\mpdf\Pdf
MODE_UTF8 'UTF-8' Unicode UTF-8 encoded mode kartik\mpdf\Pdf
ORIENT_LANDSCAPE 'L' Landscape orientation kartik\mpdf\Pdf
ORIENT_PORTRAIT 'P' Portrait orientation kartik\mpdf\Pdf

Property Details

$_css protected property

The css file content

protected string $_css null
$_mpdf protected property

Api instance

protected \Mpdf\Mpdf $_mpdf null
$_pdfAttachments protected property

List of file paths that should be attached to the generated PDF

protected array $_pdfAttachments null
$api public property

the Mpdf object instance (readonly property accessed via getter getApi())

public \Mpdf\Mpdf $api null
$content public property

The HTML content to be converted to PDF

public string $content ''
$css public property

fetches the content of the CSS file if configured (readonly property accessed via getter getCss())

public array $css null
$cssFile public property

Css files to prepend to the PDF

public array|string $cssFile '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css'
$cssInline public property

Additional inline css to append after the cssFile

public string $cssInline ''
$defaultFont public property

Sets 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.

public string $defaultFont ''
$defaultFontSize public property

Sets the default document font size in points (pt)

$destination public property

The output destination

public string $destination self::DEST_BROWSER
$filename public property

The output filename

public string $filename ''
$format public property

The format can be specified either as a pre-defined page size, or as an array of width and height in millimetres.

public string|\kartik\mpdf\array, $format self::FORMAT_A4
$marginBottom public property

Sets the page bottom margin for the new document (in millimetres).

public float $marginBottom 16
$marginFooter public property

Sets the page footer margin for the new document (in millimetres).

public float $marginFooter 9
$marginHeader public property

Sets the page header margin for the new document (in millimetres).

public float $marginHeader 9
$marginLeft public property

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.

public float $marginLeft 15
$marginRight public property

Sets the page right margin for the new document (in millimetres).

public float $marginRight 15
$marginTop public property

Sets the page top margin for the new document (in millimetres).

public float $marginTop 16
$methods public property

The Mpdf methods that will called in the sequence listed before rendering the content. Should be an associative array entered as $method => $params pairs, where:

  • $method: string, is the Mpdf method / function name
  • $param: mixed, are the Mpdf method parameters
public array $methods = []
$mode public property

Specifies the 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.

public string $mode self::MODE_BLANK
$options public property

The Mpdf configuration options entered as $key => value pairs, where:

  • $key: string, is the configuration property name
  • $value: mixed, is the configured property value
public array $options = [
    'autoScriptToLang' => true'ignore_invalid_utf8' => true'tabSpaces' => 4
]
$orientation public property

Specifies the default page orientation of the new document.

public string $orientation self::ORIENT_PORTRAIT
$pdfAttachments public property

list of file paths that should be attached to the generated PDF (readonly property accessed via getter getPdfAttachments())

public array $pdfAttachments null
$tempPath public property

The folder path for storing the temporary data generated by mpdf. If not set this defaults to path Yii::getAlias('@runtime/mpdf') which will be created if it does not exist.

public string $tempPath null

Method Details

addPdfAttachment() public method

Adds a PDF attachment to the generated PDF

public void addPdfAttachment ( $filePath )
$filePath string
execute() public method

Calls the Mpdf method with parameters

public mixed execute ( $method, $params = [] )
$method string

The Mpdf method / function name

$params array

The Mpdf parameters

throws yii\base\InvalidConfigException
getApi() public method

Validates and fetches the Mpdf API instance.

public \Mpdf\Mpdf getApi ( )
getCss() public method

Fetches the content of the CSS file if supplied

public string getCss ( )
throws yii\base\InvalidConfigException
getPdfAttachments() public method

Gets the list of currently attached PDF attachments.

public array getPdfAttachments ( )
init() public method

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )
initTempPaths() public method

Initialize folder paths to allow Mpdf to write temporary data.

public void initTempPaths ( )
output() public method

Generates a PDF output

public string output ( $content '', $file '', $dest self::DEST_BROWSER )
$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 (i.e. DEST_BROWSER).

$dest string

The output destination. Defaults to DEST_BROWSER.

throws yii\base\InvalidConfigException
throws \Mpdf\MpdfException
throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException
throws \setasign\Fpdi\PdfParser\PdfParserException
throws \setasign\Fpdi\PdfParser\Type\PdfTypeException
parseFormat() public method

Parse the format automatically based on the orientation

public void parseFormat ( )
render() public method

Renders and returns the PDF output. Uses the class level property settings.

public string render ( )
throws yii\base\InvalidConfigException
throws \Mpdf\MpdfException
throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException
throws \setasign\Fpdi\PdfParser\PdfParserException
throws \setasign\Fpdi\PdfParser\Type\PdfTypeException
setApi() public method

Sets the Mpdf API instance

public void setApi ( )
writePdfAttachment() public method

Appends the given attachment to the generated PDF

public void writePdfAttachment ( $api null, $attachment null )
$api \Mpdf\Mpdf

The Mpdf API instance

$attachment string

The attachment name

throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException
throws \setasign\Fpdi\PdfParser\PdfParserException
throws \setasign\Fpdi\PdfParser\Type\PdfTypeException