【问题标题】:Parsing raw PDF data to create PDF using PHP使用 PHP 解析原始 PDF 数据以创建 PDF
【发布时间】:2017-08-15 06:31:31
【问题描述】:

我正在访问 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);

【问题讨论】:

  • 你能提供将二进制流保存到驱动器的PHP代码吗?它看起来像损坏的二进制 PDF 流。例如。确保保存时流的末尾没有空格(不要将关闭 PHP 标记放入 PHP 脚本并使用 file_put_content)。尝试在readfile($destination) 之后添加exit()

标签: php pdf


【解决方案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();

【讨论】:

  • 这让我走上了正确的道路——问题确实是额外的内容,但之前不是之后。原来我的布局文件包含一个标题 html 块,这就是原因。
  • @Andy 我已经更新了脚本以在发送 PDF 流之前检查输出,谢谢。
  • 如何使用上面的 pdf 字符串以角度下载 pdf 文件
猜你喜欢
  • 1970-01-01
  • 2018-05-07
  • 2011-02-06
  • 2015-05-31
  • 1970-01-01
  • 2022-11-02
  • 2022-01-17
  • 2012-06-30
  • 1970-01-01
相关资源
最近更新 更多