Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calin.ionut's avatar

Download pdf file using Guzzle POST request

How can i download a pdf file from a post request using Guzzle?

I need to send some params to a url and if all it's ok i receive a pdf file. I am using laravel 5.7 for server request and ajax for client request.

What i need tot do:

  1. send some params from client to the laravel server (using post)
  2. the laravel server needs to send some params using POST to another url
  3. get the pdf file returned from step 2 to the client.

The client request with ajax to the laravel server:

$.ajax({
            type: 'POST',
            dataType: 'json',
            url: $(this).attr('data-url'),
            data: {order: $(this).attr('data-order')},
            success: function (response) {
                if(!response.error) {                    
                    swal("", response.msg, "success");
                } else {                    
                    swal("", response.msg, "error");
                }
            }
        });

The server post request on $url for getting the pdf file:

        $client = new Client();
            try{
                $response = $client->post($url,[
                    'form_params' => [
                        'nr' => $nr,
                        'username' => 'myUsername',
                        'client_id' => 'myClientID',
                        'user_pass' => 'myPassword',
                        'language' => 'ro'
                    ]
                ]);
            } catch (Exception $e){
                return response()->json(['error' => true, 'msg' => $e->getMessage() ]);
            }

If a dd the $response from guzzle:

Response {#502
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:6 [
    "Content-Type" => array:1 [
      0 => "application/pdf"
    ]
    "Server" => array:1 [
      0 => "Microsoft-IIS/8.5"
    ]
    "X-Powered-By" => array:2 [
      0 => "PHP/7.0.9"
      1 => "ASP.NET"
    ]
    "Content-Disposition" => array:1 [
      0 => "attachment; filename="2332800120195.pdf""
    ]
    "Date" => array:1 [
      0 => "Wed, 05 Dec 2018 09:58:21 GMT"
    ]
    "Content-Length" => array:1 [
      0 => "47117"
    ]
  ]
  -headerNames: array:6 [
    "content-type" => "Content-Type"
    "server" => "Server"
    "x-powered-by" => "X-Powered-By"
    "content-disposition" => "Content-Disposition"
    "date" => "Date"
    "content-length" => "Content-Length"
  ]
  -protocol: "1.1"
  -stream: Stream {#500
    -stream: stream resource @13
      wrapper_type: "PHP"
      stream_type: "TEMP"
      mode: "w+b"
      unread_bytes: 0
      seekable: true
      uri: "php://temp"
      options: []
    }
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}

How can i download the file?

0 likes
3 replies
lostdreamer_nl's avatar
Level 53

The problem here is not Guzzle, that part you already have covert, you can simply do a

$pdf = $response->getBody()->getContents();

To get the pdf in PHP.

The problem is now: An ajax request cannot simply download something.

So you have 2 options:

  • Change the ajax request into a regular POST request (the user wont really notice as you are not going to a different page, it will simply trigger the download)
  • Change your JS code

If you stick with the ajax request, the easiest way would be a bit of DOM manipulation to make the browser think you're doing a regular download:

$.ajax({
  type: 'POST',
  dataType: 'json',
  url: $(this).attr('data-url'),
  data: {order: $(this).attr('data-order')},
  success: function(data) {
    var blob=new Blob([data]);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="my-downloaded-file.pdf";
    link.click();
  }
});

It will take the response from your server, create a Blob from it, create an invisible element to link to that blob, and click it to start the download.

calin.ionut's avatar

@lostdreamer_nl If i am still using ajax, how can i send the pdf file content through json?

needs to be a blob:

new Blob([response.FileContent]);

I have tried to encode the pdf using base64_encode from php (i don't think it's the same):

return response()->json(['error' => false, 'FileContent' => base64_encode($pdf), 'FileName' => $name ]);

and it's not working.

calin.ionut's avatar

I solved the problem :)

A am using a js function to convert from base64 to blob

function b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        var blob = new Blob(byteArrays, {type: contentType});
        return blob;
    }

then from php:

return response()->json(['error' => false, 'FileContent' => base64_encode($pdf), 'ContentType' => 'application/pdf', 'FileName' => $name ]);

Please or to participate in this conversation.