Support Chinese character and special characters in PHP mPDF

Ping Cheng

--

mPDF is a super cool and easy tool that can convert your HTML content into a PDF file. I use this package a lot for my side project and private commercial projects.

Recently I just found out the mPDF doesn’t support rendering Chinese characters and some special Chinese characters by default. All these characters would be rendered as an empty block. In order to make them work properly, you would need to do some configuration to make it work.

Download font

Library mPDF contains some font files that support part of Chinese characters but not all of them, some special characters are not supported. For example, the following symbols would be converted to empty blocks.

。……“” !

In order to display correctly, we need to download a fully Chinese support font such as Microsoft Yahei. Let’s download it and place it into a directory.

/app/fonts/yahei.ttf

In this post, I would use the above path as an example.

Custom Font Configurations

Before we creating the new mPDF instance, we need to create some configuration for the custom font.

// Get the default font dirs and append the custom path to it
$defaultConfig = (new ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$fontDirs[] = '/app/fonts';
// Get the default font data and add the yahei font
$defaultFontConfig = (new FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$fontData['yahei'] = [
'R' => 'yahei.ttf'
];

Create mPDF instance

After getting our custom font configuration, we can start to initialise the mPDF instance.

$mpdf = new Mpdf([
'mode' => '+aCJK',
'setAutoTopMargin' => 'stretch',
'setAutoBottomMargin' => 'stretch',
'default_font' => 'yahei',
'fontDir' => $fontDirs,
'fontdata' => $fontData,
]);

And that is all! After we tell mPDF to use the custom font, you can just render the Chinese characters into PDFs like before.

$mpdf->WriteHTML($html);
$mpdf->Output();

--

--

Responses (1)

Write a response