如何使用 PHP 创建 PDF?

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

如何使用 PHP 创建 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;
}
登录后复制

以上就是如何使用 PHP 创建 PDF?的详细内容,更多请关注小编网其它相关文章!

转载请说明出处 内容投诉内容投诉
南趣百科 » 如何使用 PHP 创建 PDF?

南趣百科分享生活经验知识,是您实用的生活科普指南。

查看演示 官网购买