DomPDF generation for chinese characters

Alexandru Cioroianu picture Alexandru Cioroianu · Feb 10, 2015 · Viewed 7.8k times · Source

I am trying to generate a PDF that will contain Chinese characters using dompdf. Here is my code:

require('dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
mb_internal_encoding('UTF-8');
def("DOMPDF_UNICODE_ENABLED", true);
$html = ' <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
 <style>
     *{ font-family: DejaVu Sans, font-size: 12px;}
 </style> </head> <body>
 忠烈祠
  </body>
 </html>';
 $dompdf->load_html($html);
 $dompdf->render();
$output = $dompdf->output();
 $filename = 'a.pdf';
$path = $filename;
file_put_contents($path, $output);

The problem is the the generated PDF show only squares when i open it with chrome or adobe reader, but it looks ok in Mozilla firefox.

Any sugestions?

Answer

BrianS picture BrianS · Mar 3, 2015

First, move def("DOMPDF_UNICODE_ENABLED", true); above the require since the def function included with dompdf only defines the constant if it doesn't exist. When you include dompdf_config.inc.php that constant will be set at that time. Also, use define instead.

Second, you need a different font. The DejaVu fonts included with dompdf do not support CJK. For an overview read my answer to Dompdf and set different font-family.

If you do not currently have a font you might try looking up Firefly Sung. Whatever font you decide to use it should be TTF in order for dompdf to use it.

Here's an example using Firefly Sung via the @font-face CSS rule, no installation required:

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style>
    @font-face {
      font-family: 'Firefly Sung';
      font-style: normal;
      font-weight: 400;
      src: url(http://eclecticgeek.com/dompdf/fonts/cjk/fireflysung.ttf) format('truetype');
    }
    * {
      font-family: Firefly Sung, DejaVu Sans, sans-serif;
    }
  </style>
</head>

<body>
  <div>忠烈祠</div>
</body>

</html>