解析原始 PDF 数据以使用 PHP 创建 PDF



我正在访问一个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 - 正如您所期望的那样。

我还尝试在回显之前定义标头:

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

读取流后,您可能缺少一些标头或有空格。这对我有用:

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

最新更新