1. 程式人生 > 其它 >PHP 使用mPdf生成pdf檔案

PHP 使用mPdf生成pdf檔案


首先使用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
; // 設定頁首 $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(); // 輸出到頁面 // $mpdf -> Output(); // 輸出為檔案 $mpdf -> Output('./1.pdf', 'f');
歡迎轉載,轉載時請註明來源。