PHP to generate PDF

Posted May 25, 20202 min read


2. Method of generating PDF using MPDF class

mPDF is a PHP class that can generate PDF files from UTF-8 encoded HTML, it is based on FPDF and HTML2FPDF, and has many enhancements. For language processing and UTF-8 support, mpdf is better than FPDF. For CJK support, it supports not only font embedding, but also font subsets(so your CJK PDF will not be too large).

$config = [
    //Support Chinese setting
    "autoScriptToLang" => true,
    //Support Chinese setting(when Chinese garbled, set to true)
    "autoLangToFont" => true,
    "setAutoTopMargin" => "stretch",
    "setAutoBottomMargin" => "stretch",
    "autoMarginPadding" => 5,
    "margin_left" => 5,
    "margin_right" => 5

$mpdf = new \ Mpdf \ Mpdf($config);

//Set header and footer
$mpdf-> SetHTMLHeader($header);
$mpdf-> SetHTMLFooter($footer);
//Write in two columns
$mpdf-> SetColumns(2);
$mpdf-> WriteHTML($html);
//I 'means online display' D 'then display download window' F 'to save local file
$mpdf-> Output('Name of PDF.pdf', 'I');

3. MPDF custom font

<? php
namespace App \ Http \ Controllers;

use Mpdf \ Mpdf;
use Mpdf \ Config \ FontVariables;
use Mpdf \ Config \ ConfigVariables;

class ExampleController extends Controller
    public function readPDF()
        //The directory where the font text is located
        $defaultConfig =(new ConfigVariables())-> getDefaults();
        $fontDirs = $defaultConfig ['fontDir'];

        //Configured font
        $defaultFontConfig =(new FontVariables())-> getDefaults();
        $fontData = $defaultFontConfig ['fontdata'];
        $mpdf = new Mpdf([
            //Configure custom font, "lt-liti" can only be lowercase, otherwise garbled
            'fontdata' => $fontData + [
                'st-liti' => [
                    'R' => 'Chinese Lishu.TTF',
            'default_font' => 'st-liti',
            //Set the following two values   to false to enable custom fonts
            "autoScriptToLang" => false,
            "autoLangToFont" => false,
            "setAutoTopMargin" => "stretch",
            "setAutoBottomMargin" => "stretch",
            "autoMarginPadding" => 5,
            "margin_left" => 5,
            "margin_right" => 5