2016-03-24 13:57
浏览 64

Laravel 5.2 - 如何将PDF作为JSON响应的一部分返回

So I have developed an API and one of the endpoints is a report generator. Normally they send in the name of the report and some other variables and it pops out a PDF using Laravel-Snappy.

I am also using JWT-Auth for authentication. Since I need to be HIPAA compliant I will be refreshing the token on EVERY call. For most endpoints this is easy as I just add it to the meta of my json response.

However, for the reports they only return a PDF with headers to force download etc. Is there a way for me to send the PDF data as part of a JSON response that applications hitting this API would be able to use? Do I maybe need to encrypt it in some way that it can be sent with a json response? Any other ideas on any line of thought would be appreciated.

图片转代码服务由CSDN问答提供 功能建议

所以我开发了一个API,其中一个端点是一个报告生成器。 通常他们会发送报告名称和其他一些变量,然后使用 Laravel-Snappy

我还使用 JWT-Auth 进行身份验证。 由于我需要符合HIPAA标准,因此我将在每次通话时刷新令牌。 对于大多数端点来说,这很容易,因为我只是将它添加到我的json响应的元数据中。

但是,对于报告,他们只返回带有标题的PDF以强制下载等。有没有办法让我将PDF数据作为JSON响应的一部分发送给应用程序点击此API 能用吗? 我是否可能需要以某种方式对其进行加密,以便可以使用json响应进行加密? 任何其他想法都会受到赞赏。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzi0850 2016-03-24 15:21

    Never had to do this personally, but the way I've seen it in APIs is to read the file contents, base64 encode and serve that up in the json response.

    Quick bit of code

    $pdf = base64_encode(file_get_contents('path/to/my.pdf'));
    return response()->json([
        'pdf' => $pdf,

    The user can then consume this as such.

    $pdf = base64_decode($json->pdf);
    file_put_contents('path/to/save/my.pdf', $pdf);

    You should then be able to open/read the saved file as normal.

    解决 无用
    打赏 举报
  • duansao20000508 2016-03-24 19:27

    I think sending large binary data as part of JSON response is not the best idea. I would rather create temporary GET URI for PDF file with uuid or maybe more meaningful id and present it in actual JSON response. API consumer will be able to read the response and download a file.

    解决 无用
    打赏 举报

相关推荐 更多相似问题