首先使用Composer安装mPdf:
composer require mpdf/mpdf
基本使用方式:
引入:
require_once(__DIR__ . \'/vendor/autoload.php\');
在屏幕上输出“你好,世界!”为pdf文件:
$mpdf = new \Mpdf\Mpdf(); $mpdf -> autoLangToFont = true; $mpdf -> autoScriptToLang = true; $mpdf -> WriteHTML(\'你好,世界!\'); $mpdf -> Output();
其他基本使用方式:
require_once(__DIR__ . \'/vendor/autoload.php\'); // 实例化,设置上下边距为自动 $mpdf = new \Mpdf\Mpdf([\'setAutoTopMargin\' => \'stretch\', \'setAutoBottomMargin\' => \'stretch\']); // 文件属性 $mpdf -> SetTitle(\'标题\'); $mpdf -> SetAuthor(\'作者\'); // 自动匹配语言字体 $mpdf -> autoLangToFont = true; $mpdf -> autoScriptToLang = true; // 水印相关 $mpdf -> showWatermarkText = true; // 开启水印 $mpdf -> SetWatermarkText(\'水印\', 0.1); // 设置文本及透明度 $mpdf -> watermark_font = \'GB\'; // 中文支持 $mpdf -> watermarkAngle = \'22\'; // 倾斜角度 // 设置页眉 $header = <<<xmsb <div style="width: 100%; font-size: 12px; text-align: right;"> {DATE Y年m月j日} </div> <hr /> xmsb; $mpdf -> SetHTMLHeader($header); // 设置页脚 $footer = <<<xmsb <hr /> <div style="width: 100%; font-size: 12px; text-align: center;"> 第 {PAGENO} / {nb} 页 </div> xmsb; $mpdf -> SetHTMLFooter($footer); // 添加内容 $html = <<<xmsb <table border="1" cellspacing="0" cellpadding="10"> <tr><th>Header</th></tr> <tr> <td> <img src="./1.jpg" width="20%" /> </td> </tr> </table> xmsb; $mpdf -> WriteHTML($html); // 插入分页 $mpdf -> AddPage(); // 读取其他pdf的内容并插入文档 $pageCount = $mpdf -> SetSourceFile(\'1.pdf\'); for($i = 1; $i <= $pageCount; $i ++) { $mpdf -> AddPage(); $importPage = $mpdf -> ImportPage($i); $mpdf -> UseTemplate($importPage); } // 输出到页面 // $mpdf -> Output(); // 输出为文件 $mpdf -> Output(\'./1.pdf\', \'f\');