Laravel-Dompdf custom font to support Simplified Chinese

Dompdf version >= 0.6

Laravel-dompdf version >= 0.4

Disclaimer: I’m using legacy Laravel 4.2 with Laravel-dompdf 0.4. This tutorial may not work for you if you’re using another versions. Try working around the folders and dependencies for your version.

NOTE: If you’re getting a warning message about missing lib/php-font-lib/classes/Font.php, scroll to bottom for solution.

1. Download SimHei font from https://cooltext.com/Download-Font-%E9%BB%91%E4%BD%93+Sim+Hei

2. Copy the simhei.ttf file into vendor/dompdf/dompdf.

3. Edit vendor/dompdf/dompdf/dompdf_config.custom.inc.php, change these values:

define("DOMPDF_FONT_DIR", DOMPDF_DIR."/../../../app/storage/fonts/");
define("DOMPDF_FONT_CACHE", DOMPDF_DIR."/../../../app/storage/fonts/");

4. Using the command line, follow these commands (line by line, assuming you’re already in your laravel installation root folder):

cd vendor/dompdf/dompdf/
php load_font.php simhei ./simhei.ttf

5. Then in your html, simply use:

font-family: simhei;

6. Go back to step 3 (edit vendor/dompdf/dompdf/dompdf_config.custom.inc.php) and remove/comment these lines (because laravel-dompdf already defined them):

//define("DOMPDF_FONT_DIR", DOMPDF_DIR."/../../../app/storage/fonts/");
//define("DOMPDF_FONT_CACHE", DOMPDF_DIR."/../../../app/storage/fonts/");

7. Your fonts will be stored in your app/storage/fonts folder (remember to upload them to your production server).

Troubleshoot

For my case, when I run the command on step 4 above, I was thrown with this message:

PHP Warning:  require_once(/home/vagrant/sites/myproject/vendor/dompdf/dompdf/lib/php-font-lib/classes/Font.php): failed to open stream: No such file or directory in /home/vagrant/sites/myproject/vendor/dompdf/dompdf/dompdf_config.inc.php on line 334

It turns out that the dompdf installation doesn’t include the necessary files inside vendor/dompdf/dompdf/lib/php-font-lib/ (that folder is empty).

To resolve this, simply copy vendor/phenx/php-font-lib/ and paste the content into vendor/dompdf/dompdf/lib/php-font-lib/

After that, run step 4 above again and it should work.


Leave a Reply