如何使用 PHP 创建 pdf安装所需库:php 7.1 以上版本、mpdf 库。创建 pdf 文件:实例化 mpdf 对象,写入 html 内容,输出 pdf 文件。实战案例:生成用户
如何使用 PHP 创建 pdf安装所需库:php 7.1 以上版本、mpdf 库。创建 pdf 文件:实例化 mpdf 对象,写入 html 内容,输出 pdf 文件。实战案例:生成用户发票,包括客户信息、发票信息、商品列表和总额。
使用 PHP 创建 PDF
所需工具:
安装 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;
}
以上就是如何使用 PHP 创建 PDF?的详细内容,更多请关注编程网其它相关文章!
--结束END--
本文标题: 如何使用 PHP 创建 PDF?
本文链接: https://www.lsjlt.com/news/606812.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0