Home » Blog » Yii2.0 framework » Add a New Font file Into Yii2-mpdf Extension

Add a New Font file Into Yii2-mpdf Extension

Updated:   Yii2.0 framework 4 min read

Your support helps keep this blog running! Secure payments via Paypal and Stripe.


In the Yii2 framework, you want to print or export the data as a PDF file. One of the popular extensions 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 the 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 set up quickly, but a beginner may have trouble implementing 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 the yii2-mpdf extension, there is the Garuda font that comes with the extension. It seems the Garuda font displays the Thai and English characters on the screen well until I print out the PDF file from the printer. The k character prints 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 the THSarabunNew font. You can download the font from the link below.

Please complete the form. Upon successful submission, the file download will begin automatically. Please allow a few seconds for the submission to complete.

Please tell me what source led you to this post? (eg. Google, ChatGPT, StackOverflow, Reddit)
The form has been submitted successfully!
There has been some error while submitting the form. Please verify all form fields again.

Add a Custom Font to the PDF file

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

  1. Add the new font to the folder you want. I added to “webroot/themes/assets/fonts/custom“, which is my Yii2 structure I designed.
  2. Add the custom font to 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, just look at the issue in the code in the PDF class and the mPDF library document.


Your support helps keep this blog running! Secure payments via Paypal and Stripe.


Share this:
Senior WordPress Developer (Freelancer)

Senior WordPress Developer (Freelancer)

I’m a professional WordPress and WooCommerce developer based in Chiang Mai, Thailand, with over a decade of experience creating fast, secure, and scalable websites. From custom themes and plugins to full WooCommerce stores, I help businesses build a strong and reliable online presence. Need a freelance WordPress developer you can count on? View my portfolio or get in touch to discuss your project.