无法下载或打开空白PDF文件PHP

时间:2014-11-12 13:24:45

标签: php firefox pdf

我在使用firefox(ubuntu机器)的应用程序生成PDF报告时遇到了一些问题。

我的代码是:

<?php
$path = "path_to_file" ;
$file = "test.pdf";
header('Content-type: application/pdf');
header("Content-disposition: attachment; filename=$file");
readfile($path);
return new Response("Success");

代码正在运行:

  • 当PDF报告包含数据时
  • 当大小超过1 kb
  • 在Windows机器

不工作:

  • 当报告中没有数据或大小以字节为单位时。
  • 它是在浏览器的新选项卡中生成二进制sting,而不是生成blank-PDF。

请帮我解决这个问题。谢谢。

2 个答案:

答案 0 :(得分:1)

得到了我的答案。这可能对其他人有帮助。

<?php
$path = "path_to_file" ;
$file = "test.pdf";
header("Content-disposition: attachment; filename= $file"); //Tell the filename to the browser
header("Content-type: application/pdf");//Get and show report format 
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
readfile($path); //Read and stream the file
get_curret_user();

答案 1 :(得分:0)

我会这样做,以避免浏览器应用程序和缓存的一些问题。试一试:

<?php
$path = "path_to_file" ;
$file = "test.pdf";

$content = file_get_contents($path);
header("Content-disposition: attachment; filename=\"".$file."\"");
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($content));
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");
echo $content;
die();

编辑:
如果真的有必要使用浏览器的pdf插件而不是使用相关的默认pdf阅读器立即下载并打开它,请替换

header("Content-type: application/force-download");

header("Content-type: application/pdf");