0

I'm have developed a SPA (Single Page Application) with AngularJS and I'm trying to force a pdf file download with AngularJS.

By the moment I only can open de pdf file in a new tab with the next code.

HTML view:

<a ng-click="download()"></a>

Controller:

$scope.download = function(){
    $window.open('/cv.pdf', '_blank');
};

Is there any way to force the pdf download in the browser?

You can see this example in the following URLs:

www.juanmanuellopezpazos.es/curriculum (HTML View)

www.juanmanuellopezpazos.es/Curriculum.pdf (pdf file whose download I want to force)

3 Answers3

4

I am done this in MVC.NET WITH ANGULAR JS. It works fine with firefox also(Tested in version:50.0) Write down following code in your function:

//in mvc view
<a ng-href="#"   title="{{attachments.FileName}} " ng-click="download(attachment.FilePath,attachment.FileName)">{{attachments.FileName}} </a>
// in .js file
 $scope.download = function download(pathoffile, filename) {
        $http.get(pathoffile, {
            responseType: "arraybuffer"
        }).then(function (response) {
            $scope.filedata = response.data; 
            var headers = response.headers(); 
            headers['Content-Disposition'] = "attachment";
            var blob = new Blob([response.data], { type: "octet/stream" });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob); 
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }); 

    }
0

This previous question should provide quite a lot of information on this. (HTML) Download a PDF file instead of opening them in browser when clicked

In you're case I'd recommend just direct linking to the PDF and using the download attribute (http://www.w3schools.com/tags/att_a_download.asp).

Community
  • 1
  • 1
KieranDotCo
  • 467
  • 2
  • 16
0

Finally I got the solution with @kierandotco answer. The best way is something like this:

<a href="host/file.pdf" download target="_self"></a>

The download HTML5 attribute and target attribute with _self value do the trick.

Community
  • 1
  • 1