能否使用template.html模板配合TCPDF生成PDF文件?
使用TCPDF实现HTML模板生成PDF发票的方案
当然可以用TCPDF实现基于HTML模板的PDF生成,完全能适配你现有动态表格的需求,下面是具体实现思路和示例代码:
准备HTML模板文件
和DomPDF的用法逻辑一致,先编写带占位符的template.html,将发票抬头、表格数据、金额总计等动态内容用自定义标记替换,比如{{INVOICE_NUMBER}}、{{TABLE_CONTENT}}这类。示例模板片段:<!DOCTYPE html> <html> <head> <style> .invoice-header { text-align: center; margin-bottom: 20px; } .invoice-table { width: 100%; border-collapse: collapse; } .invoice-table th, .invoice-table td { border: 1px solid #000; padding: 8px; text-align: left; } .total-row { font-weight: bold; } </style> </head> <body> <div class="invoice-header"> <h1>发票</h1> <p>发票编号: {{INVOICE_NUMBER}}</p> <p>日期: {{INVOICE_DATE}}</p> </div> <table class="invoice-table"> <thead> <tr> <th>商品名称</th> <th>数量</th> <th>单价</th> <th>小计</th> </tr> </thead> <tbody> {{TABLE_CONTENT}} </tbody> <tfoot> <tr class="total-row"> <td colspan="3">总计:</td> <td>{{TOTAL_AMOUNT}}</td> </tr> </tfoot> </table> </body> </html>读取模板并替换动态内容
在PHP代码中先读取模板文件内容,再将动态生成的表格行、发票信息替换掉占位符。比如动态表格可以通过循环生成HTML行:// 读取HTML模板 $template = file_get_contents('template.html'); // 模拟动态数据(实际可从表单提交内容获取) $invoiceData = [ 'invoice_number' => 'INV-2024-001', 'invoice_date' => date('Y-m-d'), 'items' => [ ['name' => '商品A', 'qty' => 2, 'price' => 100, 'subtotal' => 200], ['name' => '商品B', 'qty' => 3, 'price' => 50, 'subtotal' => 150], ], 'total_amount' => 350 ]; // 生成动态表格内容 $tableContent = ''; foreach ($invoiceData['items'] as $item) { $tableContent .= "<tr> <td>{$item['name']}</td> <td>{$item['qty']}</td> <td>{$item['price']}</td> <td>{$item['subtotal']}</td> </tr>"; } // 替换模板中的占位符 $html = str_replace([ '{{INVOICE_NUMBER}}', '{{INVOICE_DATE}}', '{{TABLE_CONTENT}}', '{{TOTAL_AMOUNT}}' ], [ $invoiceData['invoice_number'], $invoiceData['invoice_date'], $tableContent, $invoiceData['total_amount'] ], $template);用TCPDF渲染HTML并输出PDF
初始化TCPDF实例,将处理好的HTML传入即可生成PDF:require_once('tcpdf/tcpdf.php'); // 创建TCPDF实例 $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); // 设置文档基础信息 $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('你的名称'); $pdf->SetTitle('发票'); // 关闭默认页眉页脚 $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); // 添加页面 $pdf->AddPage(); // 将HTML内容写入PDF $pdf->writeHTML($html, true, false, true, false, ''); // 输出PDF(参数'D'为下载,'I'为浏览器预览) $pdf->Output('invoice.pdf', 'D');关键注意事项
- TCPDF对CSS的支持和DomPDF有细微差异,复杂样式建议优先使用基础CSS规则,避免依赖CSS3特性
- 如果模板包含中文,需确保TCPDF配置了支持中文的字体,可通过
$pdf->SetFont('simhei', '', 12);这类代码设置 - 动态表格行数过多时,TCPDF会自动处理分页,无需额外逻辑
内容的提问来源于stack exchange,提问作者Nuno Pires
相关产品推荐
相关产品推荐

