php – 中文字符的DomPDF生成

我正在尝试使用dompdf生成包含中文字符的PDF.
这是我的代码:

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);

问题是当我用chrome或adobe reader打开它时生成的PDF只显示正方形,但它在Mozilla Firefox中看起来没问题.

任何sugestions?

解决方法

首先,移动def(“DOMPDF_UNICODE_ENABLED”,true);由于dompdf中包含的def函数仅定义常量(如果它不存在),因此高于require.当你包含dompdf_config.inc.php时,那个常量将被设置.另外,请改用define.

其次,你需要一个不同的字体. dompdf附带的DejaVu字体不支持CJK.有关概述,请阅读我对Dompdf and set different font-family的回答.

如果您当前没有字体,可以尝试查找Firefly Sung.无论您决定使用哪种字体,它都应该是TTF,以便dompdf使用它.

以下是通过@ font-face CSS规则使用Firefly Sung的示例,无需安装:

<!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>

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...