如何使用 php 創建 pdf安裝所需庫:php 7.1 以上版本、mpdf 庫。創建 pdf 文件:實例化 mpdf 對象,寫入 html 內容,輸出 pdf 文件。實戰案例:生成用戶發票,包括客戶信息、發票信息、商品列表和總額。
使用 PHP 創建 PDF
所需工具:
PHP 7.1 或以上版本
mPDF 庫
安裝 mPDF 庫:
通過 Composer 安裝 mPDF:
<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15906.html" target="_blank">composer</a> require mpdf/mpdf
登錄后復制
創建 PDF 文件:
<?php require_once __DIR__ . '/vendor/autoload.php'; $mpdf = new \mPDF(); $mpdf->WriteHTML('<h1>Hello, PDF!</h1>'); $mpdf->Output('hello-pdf.pdf', 'D');
登錄后復制
實戰案例:生成用戶發票
<?php require_once __DIR__ . '/vendor/autoload.php'; $data = [ 'user' => [ 'name' => 'John Doe', 'address' => '123 Main Street', 'city' => 'Anytown', 'zip' => '12345' ], 'invoice' => [ 'number' => 'INV-001', 'date' => '2023-03-08', 'items' => [ [ 'name' => 'Item 1', 'price' => 10, 'quantity' => 2 ], [ 'name' => 'Item 2', 'price' => 15, 'quantity' => 1 ] ] ] ]; $mpdf = new \mPDF(); $mpdf->WriteHTML(render_invoice($data)); $mpdf->Output('invoice.pdf', 'D'); function render_invoice($data) { $html = <<<HTML <h1>Invoice #{$data['invoice']['number']}</h1> <p>Date: {$data['invoice']['date']}</p> <hr> <p><strong>Customer:</strong></p> <ul> <li>{$data['user']['name']}</li> <li>{$data['user']['address']}</li> <li>{$data['user']['city']}, {$data['user']['zip']}</li> </ul> <table border="1"> <thead> <tr> <th>Item</th> <th>Price</th> <th>Qty</th> <th>Total</th> </tr> </thead> <tbody> {foreach $data['invoice']['items'] as $item} <tr> <td>{$item['name']}</td> <td align="right">{$item['price']}</td> <td align="right">{$item['quantity']}</td> <td align="right">{$item['price'] * $item['quantity']}</td> </tr> {/foreach} </tbody> <tfoot> <tr> <th co<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/79544.html" target="_blank">lsp</a>an="3" align="right">Total:</th> <td align="right">{$total_amount}</td> </tr> </tfoot> </table> HTML; return $html; }
登錄后復制