如何使用 php 创建 pdf安装所需库:php 7.1 以上版本、mpdf 库。创建 pdf 文件:实例化 mpdf 对象,写入 html 内容,输出 pdf 文件。实战案例:生成用户发票,包括客户信息、发票信息、商品列表和总额。

使用 PHP 创建 PDF
所需工具:
安装 mPDF 库:
立即学习“PHP免费学习笔记(深入)”;
通过 Composer 安装 mPDF:
composer 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 colspan="3" align="right">Total:</th>
<td align="right">{$total_amount}</td>
</tr>
</tfoot>
</table>
HTML;
return $html;
}以上就是如何使用 PHP 创建 PDF?的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号