6

解决使用 mPDF 导出 PDF 时中文及符号乱码问题

 2 years ago
source link: https://qq52o.me/2810.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解决使用 mPDF 导出 PDF 时中文及符号乱码问题

后端开发 · 实用资源 / 2022年9月11日 / 0 条评论
mPDF.png

在开发导出 PDF 时,选择了使用 mPDF,mPDF 是一个 PHP 库,它从 UTF-8 编码的 HTML 生成 PDF 文件。

而它的使用也相对简单:

使用 composer 加载

composer require mpdf/mpdf
<?php

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Hello world!</h1>');
$mpdf->Output();

但是在实际使用时会遇到中文和符号乱码(变成了小方块)的问题,最开始会想到是字体的问题,但是指定了字体后,并没有解决问题。

mpdf中文和符号乱码

查看了文档后发现需要指定两个参数:

$this->pdf = new Mpdf([
    'autoScriptToLang' => true,
    'autoLangToFont'   => true,
]);

刷新页面,发现中文此时已经可以正常显示了

mpdf中文正常,符号依旧是方块

但是当中文的标点符号靠近英文的时候,中文符号就又会变回小方块。

再添加一个配置项代码,解决符号的问题:

$this->pdf = new Mpdf([
    'autoScriptToLang' => true,
    'autoLangToFont'   => true,
    'useSubstitutions' => true,
]);

mpdf导出正常

至此,解决了中文和标点符号乱码的问题。

沈唁志
任何个人或团体,未经允许禁止转载本文:《解决使用 mPDF 导出 PDF 时中文及符号乱码问题》,谢谢合作!

如果给您解决燃眉之急或带来些许明朗,您可以打赏一杯咖啡或一杯香茗

PHP

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK