Add new font file into yii2-mpdf extension
Home » BLOG » Yii2.0 framework » Add a new font file into yii2-mpdf extension

Add a new font file into yii2-mpdf extension

category:  Yii2.0 framework

In the Yii2 framework, you want to print or export the data as a PDF file. One of popular extension is yii2-mpdf. The extension uses an mPdf library. The extension is easy to use and the document is provided. However, if you want to add a new custom font in order to use in the Pdf file, no document in yii2-mpdf extension is provided. You have to look at the document of the mPdf library instead. For an experienced web developer, you will find how to setup quicky but for the beginner may have trouble to implement it. Today I will show you how.

Two years ago I built my invoice and timesheet application by Yii2. The reason I chose Yii2 because it made me build the whole application within a few weeks. The application has been serving me well until I moved back to Thailand and started to get more Thai clients. Meaning I have to send my invoice in Thai. In yii2-mpdf extension, there is the Garuda font that comes with the extension. It seems the Garuda font displays the Thai and English character on the screen well until I print out the PDF file from the printer. The k character print out as a black square character. To fix this issue, I searched for a new Thai font that supports both Thai and English and I found THSarabunNew font. You can download the font from the link below.

Thai Sarabun New font (4423 downloads )

Add custom font into the Pdf file

Okay, we gonna add the new custom font in order to use in the PDF file. The steps will be.

  1. add the new font into the folder you want. I add into “webroot/themes/assets/fonts/custom” which is my Yii2 structure I design.
  2. add the custom font into the mPDF option.
use kartik\mpdf\Pdf; 

public function actionExport($id, $ma_currency_id, $ma_customer_id, $ma_user_id, $ma_business_id) {        
        
        // get your HTML raw content without any layouts or scripts
        $model = $this->findModel($id, $ma_currency_id, $ma_customer_id, $ma_user_id, $ma_business_id);
        $content = $this->renderPartial('_reportInvoice', [
            'model' => $model,
            'modelsInvoiceDetail' => $model->invoiceDetails, 
            'modelsInvoicePayments' => $model->invoicePayments, 
            'invoice_css' => '',
        ]);

        // instantiate Pdf object (kartik\mpdf\Pdf)
        $pdf = new Pdf([
            // set to use UTF8 encode only
            'mode' => Pdf::MODE_UTF8,
            
            // 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,
            
            // given filename
            'filename' => 'Invoice_No_' . $id . '.pdf',                        

            /**
             * set the custom font in cssInLine options
             * https://mpdf.github.io/fonts-languages/default-font.html
             * the font-family and font-size must set in the cssInLine here. 
             */
            'cssInline' => '*,body{font-family:thsarabun;font-size:14pt}',

            // set mPDF properties on the fly
            'options' => ['title' => 'Invoice No_'. $model->id],
            
            // call mPDF methods on the fly
            'methods' => [
                // link: https://mpdf.github.io/headers-footers/method-2.html
                'SetFooter' => ['<div style="text-align:center; font-weight:normal; font-family:thsarabun; font-size:12pt; font-style: italic;">' . 'Invoice No.' . $id . ' - {PAGENO} / {nb} </div>'],
            ],            
        ]);


        /**
         * Add new custom font in Mpdf library
         * link: https://mpdf.github.io/fonts-languages/fonts-in-mpdf-7-x.html
         */
        $defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
        $fontDirs = $defaultConfig['fontDir'];

        $defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
        $fontData = $defaultFontConfig['fontdata'];

        /**
         * We set more options as showing in "vendors/kartik-v/yii2-mpdf/src/Pdf.php/Pdf/options" method
         * What we do, we merge the options array to the existing one.
         */
        $pdf->options = array_merge($pdf->options , [
            'fontDir' => array_merge($fontDirs, [ Yii::$app->basePath . '/themes/assets/fonts/custom']),  // make sure you refer the right physical path
            'fontdata' => array_merge($fontData, [
                'thsarabun' => [
                    'R' => 'THSarabunNew.ttf',
                    'I' => 'THSarabunNew Italic.ttf',
                    'B' => 'THSarabunNew Bold.ttf',
                ]
            ])
        ]);
        // # print out the pdf object to see all properties that we just set above.
        // var_dump($pdf);
        // exit;


        // return the pdf output as per the destination setting
        return $pdf->render();        
    }  

That’s it. If you have any issues, you just look at the code in pdf class and the mPdf library document.