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


not able to download or open blank PDF file PHP

我在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报告包含数据时
  • 当大小大于1kb时
  • 开窗机

不工作:

  • 当报表不包含数据或大小以字节为单位时
  • 它是在浏览器的新选项卡中生成二进制字符串,而不是生成空白PDF

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

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

<?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();

我会用这种方式来避免浏览器应用程序和缓存方面的一些问题。试试看:

<?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");