本文目录导读:

在PHP中将HTML转换为PDF有多种实现方式,以下是几种常用的方法:
使用 Dompdf(最常用)
安装
composer require dompdf/dompdf
基本使用
<?php
require_once 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
// 创建实例
$options = new Options();
$options->set('defaultFont', 'Helvetica');
$dompdf = new Dompdf($options);
// HTML内容
$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">PDF示例</title>
<style>
body { font-family: "Helvetica", sans-serif; }
h1 { color: #333; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; }
</style>
</head>
<body>
<h1>用户列表</h1>
<table>
<tr><th>姓名</th><th>年龄</th></tr>
<tr><td>张三</td><td>28</td></tr>
<tr><td>李四</td><td>32</td></tr>
</table>
</body>
</html>';
// 加载HTML
$dompdf->loadHtml($html);
// 设置纸张大小和方向
$dompdf->setPaper('A4', 'portrait');
// 渲染PDF
$dompdf->render();
// 输出PDF
$dompdf->stream("document.pdf", array("Attachment" => false));
// 保存到文件
// file_put_contents('document.pdf', $dompdf->output());
使用 mPDF
安装
composer require mpdf/mpdf
使用示例
<?php
require_once 'vendor/autoload.php';
use Mpdf\Mpdf;
// 创建实例
$mpdf = new Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'margin_left' => 10,
'margin_right' => 10,
'margin_top' => 10,
'margin_bottom' => 10
]);
// HTML内容
$html = '
<h1>报告标题</h1>
<p>这是一段文字内容。</p>
<p>可以有图片:</p>
<img src="path/to/image.jpg" width="200">
';
// 写入HTML
$mpdf->WriteHTML($html);
// 输出PDF
$mpdf->Output('document.pdf', 'D'); // D=下载, I=内联显示, F=保存到文件
使用 wkhtmltopdf(推荐处理复杂HTML)
安装 wkhtmltopdf
# Ubuntu/Debian sudo apt-get install wkhtmltopdf # 或者下载二进制文件
使用示例(通过PHP执行命令)
<?php
// HTML内容
$html = '
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Microsoft YaHei", sans-serif; }
</style>
</head>
<body>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</body>
</html>';
// 保存HTML到临时文件
$htmlFile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($htmlFile, $html);
// 指定输出PDF路径
$pdfFile = tempnam(sys_get_temp_dir(), 'pdf') . '.pdf';
// 执行wkhtmltopdf命令
$command = "wkhtmltopdf --encoding utf-8 '{$htmlFile}' '{$pdfFile}' 2>&1";
exec($command, $output, $returnVar);
// 输出PDF
if (file_exists($pdfFile)) {
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="document.pdf"');
readfile($pdfFile);
}
// 清理临时文件
unlink($htmlFile);
unlink($pdfFile);
使用 TCPDF
安装
composer require tecnickcom/tcpdf
使用示例
<?php
require_once 'vendor/autoload.php';
// 创建PDF对象
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 设置文档信息
$pdf->SetCreator('Your App');
$pdf->SetAuthor('Author Name');
$pdf->SetTitle('Document Title');
// 添加页面
$pdf->AddPage();
// HTML内容
$html = '
<h1>TCPDF示例</h1>
<p>这是一个使用TCPDF生成的PDF文档。</p>
<table border="1">
<tr><td>单元格1</td><td>单元格2</td></tr>
<tr><td>单元格3</td><td>单元格4</td></tr>
</table>
';
// 写入HTML
$pdf->writeHTML($html, true, false, true, false, '');
// 输出PDF
$pdf->Output('document.pdf', 'I');
处理中文字体
对于中文支持,需要在代码中配置:
Dompdf 配置中文
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans'); // 支持中文
$dompdf = new Dompdf($options);
// 或者使用自定义字体
$fontDir = __DIR__ . '/fonts';
$dompdf->addFont('simsun', '', $fontDir . '/simsun.ttf');
mPDF 配置中文
$mpdf = new Mpdf([
'mode' => 'utf-8',
'autoScriptToLang' => true,
'autoLangToFont' => true
]);
// 添加中文字体
$mpdf->AddFont('simsun', '', 'simsun.ttf', true);
完整示例:使用 Dompdf + API
<?php
// api/generate-pdf.php
require_once 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
header('Content-Type: application/json');
try {
// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);
$html = $input['html'] ?? '';
if (empty($html)) {
throw new Exception('HTML内容不能为空');
}
// 配置DomPDF
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true); // 允许加载远程图片
$options->set('defaultFont', 'DejaVu Sans');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// 直接输出PDF流
$dompdf->stream("document.pdf", array("Attachment" => false));
} catch (Exception $e) {
echo json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
选择建议
| 工具 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| Dompdf | 纯PHP, 简单易用 | 复杂CSS支持有限 | 简单HTML到PDF |
| mPDF | CSS支持好, 功能丰富 | 较大 | 复杂文档 |
| wkhtmltopdf | 渲染效果好 | 需要安装外部工具 | 高质量PDF |
| TCPDF | 功能强大 | 学习曲线陡 | 专业PDF生成 |
选择哪个工具主要取决于你的需求:
- 简单应用:Dompdf
- 复杂布局:mPDF 或 wkhtmltopdf
- 专业PDF:TCPDF