简体   繁体   中英

Laravel 5.2 - How to return a PDF as part of a JSON response

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM