【发布时间】:2016-04-08 13:04:24
【问题描述】:
在浏览器中以编程方式(通过 PHP)生成 PDF 时,呈现的 PDF 在 Firefox 和 Safari 中都可以正常显示,但 Chrome 会返回 ERR_INVALID_RESPONSE。它是一个有效的 PDF - 一旦从工作浏览器保存,就可以使用 Adobe Reader/Preview 在本地打开,一旦从其他浏览器保存 PDF,它甚至可以在 Chrome 中打开。
PDF 文件正在通过file_get_contents() 读取,被赋予当前时间戳,然后传递给浏览器。解决方法是将文件保存到临时位置并重定向用户(至少对于 Chrome),但这并不理想。
我已经研究过了,只能找到bug reports dating from 2008。
我知道这是一个标题错误。生成 PDF 后,将以下标头发送到浏览器(在 FF、Safari 和 IE 中再次正常工作):
header('Content-type:application/pdf');
header("HTTP/1.1 200 OK");
我也尝试在 Stack Overflow 上搜索后添加以下标题,但无济于事:
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
是否缺少 Chrome 所需的标头?有没有人有让动态生成的 PDF 在 Chrome 中显示的经验?
编辑:我的一个更突出的问题是什么可能导致它在 Chrome 本地运行良好,但不能在服务器环境中运行。
【问题讨论】:
-
您是否尝试过将配置更改为附件? header('Content-Disposition: attachment;; filename="YourFileName"');
-
@HNA 我有 - 无论是否使用附件,Chrome 都会出现同样的错误。有两个按钮:“保存”,它会抛出
header('Content-Disposition: attachment;');,以便自动下载文件(这在 Chrome、FF 和 Safari 中本地运行,并且在 Safari 和 Firefox 中非本地运行)。另一个按钮“查看”仅显示 PDF 而不会自动下载。目前两者都不能在非本地实例中的 Chrome 中工作。 -
您发送
header('Content-Length: ' . filesize($yourfile));吗? -
@maxhb 是的。以下标头随请求一起发送:
header('Content-Type: application/pdf');header('Content-Disposition: inline; filename="' . $filename . '"');header('Expires: 0');header('Cache-Control: must-revalidate, post-check=0, pre-check=0');header('Pragma: public');header('Content-Length: ' . $length); -
Chrome 首先需要 Status 200 Header。这有效: header( $_SERVER["SERVER_PROTOCOL"] . ' 200 OK' ); header('内容类型:应用程序/pdf'); header('Content-Disposition: inline; filename="' . $filename . '"' ); header('内容传输编码:二进制'); header('接受范围:字节');
标签: php google-chrome pdf