How to use mPDF for Chinese Language

2019-02-20 16:48发布

I am using mPDF to save form input data to PDF. For English, it is working fine. Anyone can use this code to save HTML Form data to PDF.

Issue: In order to fulfill my project requirement I need to use the Chinese Language. My current code is not working for that.

Form.html

<form action='processPDF.php' method='post'>
    <label for="name">Name</label>
    <input name="name" type="text" id="name">
    <input type='submit' name='submit' value='Download PDF'>
</form>

processPDF.php

<?php
header('Content-Type: text/html; charset=UTF-8');
if (isset($_POST['submit'])) {
    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    } else {
        $Larmtid = '';
    }
    if (!isset($error)) {
        ob_start();
?>        
<div style="padding:20px;">
            <p>Name: <?php
        echo $name;
?></p>
        </div>
        <?php
        $body = ob_get_clean();
        $body = iconv('UTF-8', 'UTF-8//IGNORE', $body);
        $body = iconv('UTF-8', 'UTF-8//TRANSLIT', $body);
        include("mpdf/mpdf.php");
        $mpdf = new \mPDF('c', 'A4', '', '', 0, 0, 0, 0, 0, 0);
        $mpdf->SetAutoFont();
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont   = true;
        $mpdf->WriteHTML($body);
        $mpdf->Output('SavePDF.pdf', 'D');
    }

}
?>

The problem I am having is: In the input field, I typed 怎么用中文说话 and it prints ��������.

If you want to download the source code here is the link to the code

2条回答
聊天终结者
2楼-- · 2019-02-20 17:04

Do not use 'c' as a $mode parameter, that means PDF core fonts only and they do not support chinese characters.

Try '+aCJK' or '-aCJK' instead.

See examplefiles using chinese font.

查看更多
萌系小妹纸
3楼-- · 2019-02-20 17:23

My Code is as follow [mpdf v7.0 from composer]

<?php
require_once './vendor/autoload.php';
//report errors
error_reporting(E_ALL);
ini_set("display_errors", 1);

$config = [
    'mode' => '+aCJK', 
    // "allowCJKoverflow" => true, 
    "autoScriptToLang" => true,
    // "allow_charset_conversion" => false,
    "autoLangToFont" => true,
];
$mpdf=new \Mpdf\Mpdf($config);

$mpdf->WriteHTML('Hello World 中文');
$mpdf->Output();

This code works fine, you can try it

查看更多
登录 后发表回答