如何在PHP中实现FPDF生成的PDF页面加载时自动下载?
实现FPDF生成PDF并自动下载的解决方案
嘿,我来帮你搞定这个自动下载PDF的需求!你现有的代码已经具备生成PDF的基础,只需要添加几行HTTP响应头设置,就能让PDF在页面加载时自动触发下载,而不是在浏览器中预览。
关键要点说明
要实现自动下载,需要明确告诉浏览器两件事:
- 当前响应内容是标准PDF格式(通过
Content-Type头声明) - 应该将文件作为附件下载,而非在线打开(通过
Content-Disposition头控制)
另外FPDF的Output()方法也支持直接指定下载行为,两种方式都能达到目的,我会在代码里展示最直观的写法。
完整修正代码
<?php require('fpdf17/fpdf.php'); // 初始化PDF对象 $pdf = new FPDF(); $pdf->AddPage(); $date = date('Y-m-d'); $width_cell = array(75, 75, 40); // 设置标题字体和内容 $pdf->SetFont('Arial', 'B', 20); $pdf->Cell(50, 10, "Contact List( Downloaded on " . $date . ")"); $pdf->Ln(); $pdf->Ln(); // 设置表格字体和表头填充色 $pdf->SetFont('Arial', '', 14); $pdf->SetFillColor(193, 229, 252); // 绘制表头单元格 $pdf->Cell($width_cell[0], 10, 'Name', 1, 0, 'C', true); $pdf->Cell($width_cell[1], 10, 'Email', 1, 0, 'C', true); $pdf->Cell($width_cell[2], 10, 'Phone', 1, 1, 'C', true); // 示例表格数据(可替换为你的实际数据源) $pdf->SetFont('Arial', '', 12); $pdf->Cell($width_cell[0], 10, 'John Doe', 1, 0, 'L'); $pdf->Cell($width_cell[1], 10, 'john@example.com', 1, 0, 'L'); $pdf->Cell($width_cell[2], 10, '123-456-7890', 1, 1, 'L'); $pdf->Cell($width_cell[0], 10, 'Jane Smith', 1, 0, 'L'); $pdf->Cell($width_cell[1], 10, 'jane@example.com', 1, 0, 'L'); $pdf->Cell($width_cell[2], 10, '987-654-3210', 1, 1, 'L'); // 设置响应头,强制触发下载 header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="contact_list_' . $date . '.pdf"'); // 输出PDF文件 $pdf->Output(); ?>
额外提示
- 如果你更习惯用FPDF内置的参数控制下载,也可以把最后两行替换成:
$pdf->Output('D', 'contact_list_' . $date . '.pdf');,效果完全一致 - 务必保证在调用
header()之前没有任何输出(包括空格、HTML标签、echo内容等),否则会导致头信息发送失败,PDF无法正常下载
内容的提问来源于stack exchange,提问作者thejas das
相关产品推荐
相关产品推荐

