我正在尝试使用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阅读器打开生成的PDF时,它只显示正方形,但在Mozilla firefox中看起来还可以。
有什么建议吗?
首先,将def("DOMPDF_UNICODE_ENABLED", true);
移到require之上,因为dompdf中包含的def
函数只在常量不存在的情况下定义常量。当您包含dompdf_config.inc.php时,将在那时设置该常量。另外,请改用define
。
第二,你需要一个不同的字体。dompdf中包含的DejaVu字体不支持CJK。有关概述,请阅读我对Dompdf的回答,并设置不同的字体系列。
如果您目前没有字体,您可以尝试查找萤火虫宋。无论你决定使用什么字体,都应该是TTF,以便dompdf使用它。
下面是一个通过@font face CSS规则使用萤火虫宋的例子,无需安装:
<!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>