Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i tried to download PDF from external URL in angularjs but i failed to download following is my code

<!DOCTYPE html>
<html>

  <head>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js"> </script>    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
    
    
  </head>

  <body>
   
    <div ng-app="myApp" ng-controller="myCtrl">
 <button ng-click="downloadPdf()" >Download PDF</button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.downloadPdf = function (ServicePDF) {
            var fileName = "file_name.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            ServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([result.data], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
                a.download = fileName;
                a.click();
            });
        };
        
  app.factory('ServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});   
   
});
</script>
  </body>

</html>


What I have tried:

i couldn't find any code on .net
Posted
Updated 12-Dec-19 12:00pm

The above code worked for me in angular 2+ application

The notable edits I made to work:

changed from
var file = new Blob([result.data], {type: 'application/pdf'});

to
var file = new Blob([result], {type: 'application/pdf'});


and
from this
$http.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });


to

$http.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', { responseType: 'arraybuffer' });
 
Share this answer
 
v4
For IE just add this:
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
   window.navigator.msSaveOrOpenBlob(result, fileName);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900