1

enter image description here

I am using below code for downloading PDF files.File is downloaded but doesn't contain any data.

     var blob = new Blob([response], { type: "text/plain"});
     var url = window.URL.createObjectURL(blob); 
     var link = document.createElement('a');
     link.href = url;
     link.download = e.coAttachmentName; 
     link.click();
Vijay Krishna
  • 112
  • 12
krish
  • 79
  • 1
  • 8
  • This Reference will help you: https://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app – Vijay Krishna Nov 07 '17 at 07:00

2 Answers2

3

Use FileSaver.js, get it from here https://github.com/eligrey/FileSaver.js/

var filename = new Date();
var blob = new Blob([response], {type: "application/pdf;charset=utf-8"});
saveAs(blob, filename +".pdf");

saveAs will download a pdf file for you.

skdonthi
  • 1,308
  • 1
  • 18
  • 31
2

First of all your request response type has to be arraybuffer.

function openFile(response,fileName,saveFile){
  var fileURL;
  var contentType = response.headers('Content-Type');
  var blob = new $window.Blob([response.data], { type: contentType });
  if(saveFile){
      saveAs(blob, fileName);
  }else{
    if($window.navigator.msSaveOrOpenBlob){
        $window.navigator.msSaveOrOpenBlob(blob , fileName);
    }else{
        fileURL = URL.createObjectURL(blob);
        $window.open(fileURL, '_blank');
    }
  }
}

$window is an AngularJS service - reference to browers window object.

$window.navigator.msSaveOrOpenBlob - it's a method specific to IE browser that supports creating and downloading files insted of Blob URL which isn't supported by IE.

saveAs - https://github.com/eligrey/FileSaver.js/

krutkowski86
  • 1,084
  • 9
  • 16