Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 727
Gabriele Falace Avatar asked Nov 05 '14 10:11

Gabriele Falace


People also ask

How do you save a PDF that Cannot be saved?

Ideally, if you want to learn how to save a PDF that cannot be saved, then you need to open your document correctly. For instance, you can just right-click the PDF file, go to the “Open with” feature, and select the installed PDF application.

How do I save a PDF document?

To save a PDF, choose File > Save or click the Save File icon in the Heads Up Display (HUD) toolbar at the bottom of the PDF. The Save As dialog box is displayed. Choose the location where you want to save the PDF and then click Save.

How do I save a PDF to gallery?

Open the PDF in Acrobat, and then choose Tools > Export PDF. The various formats to which you can export the PDF file are displayed. Click Image and then choose the image file format that you want to save the images in.


1 Answers

$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.

like image 155
Eli Grey Avatar answered Sep 27 '22 17:09

Eli Grey