php实现pdf下载
使用PHP实现PDF下载功能
使用header()函数强制下载
设置HTTP头信息,强制浏览器下载PDF文件而非直接打开。
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
header('Content-Length: ' . filesize('path/to/file.pdf'));
readfile('path/to/file.pdf');
exit;
从URL下载PDF并转发给用户
适用于需要从远程服务器获取PDF文件的情况。
$file_url = 'http://example.com/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($file_url);
exit;
使用FPDF生成PDF并下载
动态生成PDF文件并提供下载。

require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="generated.pdf"');
echo $pdf->Output('S');
exit;
使用TCPDF库下载PDF
TCPDF是另一个流行的PHP PDF生成库。
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->writeHTML('<h1>Sample PDF</h1>');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="tcpdf_sample.pdf"');
echo $pdf->Output('sample.pdf', 'S');
exit;
处理大文件下载
对于大文件,使用分块读取方式避免内存问题。

$file = 'large_file.pdf';
$chunk_size = 1024*1024; // 1MB chunks
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
安全考虑
验证用户权限后再允许下载,防止未授权访问。
session_start();
if (!isset($_SESSION['logged_in'])) {
die('Access denied');
}
$safe_file = basename($_GET['file']);
$file_path = '/secure/path/to/pdfs/' . $safe_file;
if (file_exists($file_path)) {
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.$safe_file.'"');
readfile($file_path);
exit;
} else {
die('File not found');
}
使用Composer包管理
通过Composer安装PDF处理库更便捷。
composer require tecnickcom/tcpdf
composer require setasign/fpdf
以上方法涵盖了从静态文件下载、远程文件获取到动态生成PDF的各种场景,可根据具体需求选择适合的实现方式。注意在生产环境中应添加适当的安全验证和错误处理机制。






