【问题标题】:Open REST API response in pdf from browser从浏览器以 pdf 格式打开 REST API 响应
【发布时间】:2021-03-07 15:16:16
【问题描述】:

我在浏览器中从 REST API 响应打开 PDF 文档时遇到问题。

我的PHP函数如下:

<?php 
function printdocument(){
$documentArray = array(
     array('doc' => array('id' => '20613')),
);
#-> The JSON data.
$jsonData = array(
   'userName' => 'username',
   'password' => 'password',
   'paperSize' => 'A4',
   'parcels' => $documentArray
);
$jsResponse = apiRequest(https://api.call.com/print/', $jsonData);
header("Content-type: application/octet-stream");
header('HTTP/1.1 200 OK');
header('Content-type:application/pdf');
echo $jsResponse;
}
?>

几乎所有浏览器都收到错误消息:

Error
Failed to load PDF document.

【问题讨论】:

  • 您确定 api 返回的是 pdf 文档而不是 base64 文本。如果是 base64,你应该先运行 base64_decode。并且无需设置多个内容类型标头。试试这个 header('Content-type: ' . 'application/octet-stream'); header('Content-Disposition: ' . '附件; filename=filename.pdf');回声 $jsResponse;

标签: php api rest


【解决方案1】:
header("Content-type: application/octet-stream");
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");

这解决了问题,但现在 PDF 文档被强制下载而不是在预览中打开。我更喜欢在浏览器预览中加载它而不是下载。

您能分享一下您的意见吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2021-07-28
    • 2015-10-02
    • 2017-11-09
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    相关资源
    最近更新 更多