dompdf 中文乱码问题处理

技术 置顶 精帖
0 379
peng49
peng49 2023-09-20 14:05:30
 

显示中文乱码是因为默认的字体不支持中文,引入一个支持中文的字体就可以了

  1. //指定字体保存的目录
  2. //支持加载远程图片 'isRemoteEnabled' => true
  3. $dompdf = new Dompdf\Dompdf(['chroot' => 'C:/Windows/Fonts']);
  4. //加载字体
  5. $dompdf->getFontMetrics()
  6. ->registerFont(
  7. [
  8. 'family' => 'Custom Font',
  9. 'style' => 'normal',
  10. 'weight' => 'normal'
  11. ],
  12. 'C:/Windows/Fonts/simhei.ttf'
  13. );
  14. $dompdf->loadHtml('<body>Chinese 中文</body><style>@page{margin:0;padding:0;}body{font-family: "Custom Font";}</style>');
  15. $dompdf->setPaper('C7', 'landscape');
  16. $dompdf->render();
  17. $pdfContent = $dompdf->output();
  18. //保存文件未DOMPDF.pdf
  19. file_put_contents('./DOMPDF.pdf', $pdfContent);

指定PDF的宽高,现在html中设置body的宽和高,然后在php中设置生成的PDF的宽高

  1. https://github.com/dompdf/dompdf/issues/1524
  2. //渲染第一次,通过回到获取到渲染时的实际高度
  3. $dompdf = new Dompdf\Dompdf(['chroot' => 'C:/Windows/Fonts','isRemoteEnabled' => true]);
  4. //加载字体
  5. $dompdf->getFontMetrics()
  6. ->registerFont(
  7. [
  8. 'family' => 'Custom Font',
  9. 'style' => 'normal',
  10. 'weight' => 'normal'
  11. ],
  12. 'C:/Windows/Fonts/simhei.ttf'
  13. );
  14. $dompdf->loadHtml('<body>Chinese 中文</body><style>@page{margin:0;padding:0;}body{font-family: "Custom Font";}</style>');
  15. $GLOBALS['bodyHeight'] = 0;
  16. $dompdf->setCallbacks(array(
  17. 'myCallbacks' => array(
  18. 'event' => 'end_frame', 'f' => function ($infos) {
  19. $frame = $infos->get_frame();
  20. if (strtolower($frame->get_node()->nodeName) === "body") {
  21. $padding_box = $frame->get_padding_box();
  22. $GLOBALS['bodyHeight'] += $padding_box['h'];
  23. }
  24. }
  25. )
  26. ));
  27. $dompdf->setPaper([0,0,286,286], 'landscape');
  28. $dompdf->loadHtml($html);
  29. $dompdf->render();
  30. unset($dompdf);
  31. //再通过获取到的高度重新渲染一遍获得新的pdf
  32. $dompdf = new Dompdf\Dompdf(['chroot' => 'C:/Windows/Fonts','isRemoteEnabled' => true]);
  33. //加载字体
  34. $dompdf->getFontMetrics()
  35. ->registerFont(
  36. [
  37. 'family' => 'Custom Font',
  38. 'style' => 'normal',
  39. 'weight' => 'normal'
  40. ],
  41. 'C:/Windows/Fonts/simhei.ttf'
  42. );
  43. $dompdf->setPaper(array(0,0,286,$GLOBALS['bodyHeight']));
  44. $dompdf->loadHtml('<body style="width:100mm;height:100mm">Chinese 中文</body><style>@page{margin:0;padding:0;}body{font-family: "Custom Font";}</style>');
  45. $dompdf->render();
  46. $dompdf->stream();

参考链接

Dompdf and set different font-family
pdf加载远程图片
div居中问题处理,推荐方法三

回帖
登录
忘记密码?