CookieMonster's avatar

How to download pdf file from external api response?

I need to download files from an api response. For example:

              $url = "https://api-sandbox.xxxxx.co/SG/2.0/reports/waybill?tids=MYKPSxxxxxxxx&h=0";
                        $response = Http::withToken($token)->get($url);
                        $data = $response->getBody()->getContents();
                        $pdf = PDF::loadView('pdf.airbill',compact('data'))->setPaper('A4');
                        return $pdf->stream('airbill.pdf');
                        dd($response->getBody()->getContents());

After calling the api, I received null from response $response->json() as the response returns a pdf file directly(not url to download the pdf file). I figured I do not need to use dompdf as well to make another HTML to pdf which was already given from the response.

Based on getContents(), it returns a long list of encoded contents for the PDF so I want to download the pdf and save to my db. Any help is appreciated.

0 likes
8 replies
Sinnbeck's avatar

What happens if you just store it to a file?

file_put_contents('path_to_file.pdf', $response->getBody()->getContents());
CookieMonster's avatar

@Sinnbeck I just tested your solution. It created a path_to_file.pdf file in the public directory. I can view it in the browser via the path, so I should save the path to my db?

Sinnbeck's avatar

@nickywan123 Its a pdf so you would need to open it with a pdf reader. But are you trying to send the content to the browser?

return response()->streamDownload(function () {
   $url = "https://api-sandbox.xxxxx.co/SG/2.0/reports/waybill?tids=MYKPSxxxxxxxx&h=0";
   $response = Http::withToken($token)->get($url);
    echo $response->getBody()->getContents();
}, 'myfile.pdf');
CookieMonster's avatar

@Sinnbeck Actually I wanted to save the file or path in my db(airbill column) so when I view my order history page(display tracking number, order date, amount, airbill....) where I can click on airbill and it returns a PDF for me to view on browser as well to download it.

CookieMonster's avatar

@Sinnbeck Yes I can open the file based on your first suggestion.

Do i use this response according to the docs instead of file_put_contents:

return response()->file($pathToFile);

?

Sinnbeck's avatar

@nickywan123 Yes you can do that to show the pdf after it has been downloaded locally.. or the streamed response I showed above

Cagdi88's avatar

hi , i tested the solution from Sinnbeck, but the file seems to be not valid when its downloaded to the browser. File is broken, on the server the file is working correct.

Please or to participate in this conversation.