Gabriele Falace
Gabriele Falace

Reputation: 71

Saving a PDF returned by service

I'm using FileSaver.js and Blob.js into an Angular JS application to save a PDF returned by a REST service (which returns an array of bytes representing the file).

var headers = {headers: {"Authorization":"Bearer "+token, "Accept":"application/pdf"}};

  $http.get(URL, headers)
    .success(function (data) {
      var blob = new Blob([data], {type: 'application/pdf'});
      saveAs(blob, 'contract.pdf');
    });

the file gets saved with the right type and the number of pages is correct, but it's totally blank. Opening it with an editor, it turned out the it contains only the first part of the data returned by the server, like it's truncated.

Thank everyone for helping out!

Upvotes: 7

Views: 5750

Answers (2)

Phil
Phil

Reputation: 1069

Adding a response type to the config argument worked for me. Try:

var config = { responseType: 'blob', headers: {"Authorization":"Bearer "+token, 
"Accept":"application/pdf"}};

  $http.get(URL, config)
      .success(function (data) {
          var blob = new Blob([data], {type: 'application/pdf'});
          saveAs(blob, 'contract.pdf');
       });

Upvotes: 0

Eli Grey
Eli Grey

Reputation: 35870

$http.get probably isn't handling binary data correctly. Try $http({method: "GET", url: URL, responseType: "arraybuffer", ...}) (see angularjs) to get a binary object you can put in for data.

You can also use responseType: "blob" so you don't even have to create var blob, but I think that responseType has less browser support.

Upvotes: 8

Related Questions