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!
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.
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.
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.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With