我正在访问API以下载/查看采购订单的PDF。
API正在返回看起来像是原始PDF数据的内容:
%PDF-1.2
%����
4 0 obj
<<
/E 12282
/H [1239 144]
/L 12655
/Linearized 1
/N 1
/O 7
/T 12527
我很难找到将其转换为可下载PDF或在浏览器中呈现PDF的方法。
我正在使用PHP,我尝试回应响应,这只是完整显示原始PDF - 正如您所期望的那样。
我也尝试在echo之前定义标题:
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=purchase.pdf");
header("Content-Transfer-Encoding: binary");
这会生成下载,但是当您打开它时,我会收到“无法加载pdf文档”错误。
我已经找到了一种方法来做到这一点,但找不到任何接近我遇到的问题的方法。我需要用TCPDF之类的东西来解析这个响应,还是我错过了一些非常明显的东西?
更新:
使用下面的代码,我可以将文件保存到服务器,如果我下载它,它会打开并且正如我所期望的那样,但我仍然无法在浏览器中提供它。
$data = $results->body;
$destination = '../pos/'.$id.'.pdf';
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
$filename = $id.'.pdf';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($destination);
答案 0 :(得分:1)
您可能在阅读流后丢失了一些标题或空格。这对我有用:
$path = '/file/absolute/path.pdf';
$content = '%PDF-1.4%âãÏÓ8 0 obj<< /Type ....';
// save PDF buffer
file_put_contents($path, $content);
// ensure we don't have any previous output
if(headers_sent()){
exit("PDF stream will be corrupted - there is already output from previous code.");
}
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download dialog
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
// use the Content-Disposition header to supply a recommended filename
header('Content-Disposition: attachment; filename="'.basename($path).'";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path));
header('Content-Type: application/pdf', false);
// send binary stream directly into buffer rather than into memory
readfile($path);
// make sure stream ended
exit();