通过设置 Content-Type: application/pdf 响应头,配合 readfile() 直接将 PDF 文件二进制流输出到浏览器,浏览器内置或插件 PDF 查看器即可直接渲染,无需下载到本地。
<?php
if (!function_exists('read_pdf')) {
function read_pdf($file) {
// 校验扩展名
if (strtolower(substr(strrchr($file, '.'), 1)) != 'pdf') {
echo '文件格式不正确,仅支持 PDF。';
return;
}
// 校验文件存在
if (!file_exists($file)) {
echo '文件不存在。';
return;
}
// 设置响应头
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// 输出文件流
readfile($file);
}
}
// 使用示例
read_pdf('Python_study.pdf');
Content-Disposition: inline 告诉浏览器尝试在页面内打开而非下载;若需强制下载改为 attachment。readfile() 直接将文件读入输出缓冲区,内存效率高,适合大文件(配合 ob_end_clean() 避免前置输出)。fread($fp, 8192) 循环输出,并配合 flush()。filename*=UTF-8'' + rawurlencode() 编码(RFC 5987)。