How to Display blob (.pdf) in an AngularJS app

The question:

I have been trying to display pdf file which I am getting as a blob from a $ response. The pdf must be displayed within the app using <embed src> for example.

I came across a couple of stack posts but somehow my example doesn’t seem to work.


According to this doc, I went on and tried…

$'/postUrlHere',{myParams}).success(function (response) {
 var file = new Blob([response], {type: 'application/pdf'});
 var fileURL = URL.createObjectURL(file);
 $scope.content = fileURL;

Now from what I understand, fileURL creates a temporary URL that the blog can use as a reference.


<embed src="{{content}}" width="200" height="200"></embed>

I am not sure how to handle this in Angular, the ideal situation would be to (1) assign it to a scope, (2) ‘prepare/rebuild’ the blob to a pdf (3) pass it to the HTML using <embed> because I want to display it within the app.

I have been researching for more than a day now but somehow I can’t seem to understand how this works in Angular… And let’s just assume the pdf viewer libraries out there weren’t an option.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

First of all you need to set the responseType to arraybuffer. This is required if you want to create a blob of your data. See Sending_and_Receiving_Binary_Data. So your code will look like this:

$'/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);

The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:

$scope.content = $sce.trustAsResourceUrl(fileURL);

Do not forget to inject the $sce service.

If this is all done you can now embed your pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

Method 2

I use AngularJS v1.3.4


<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

JS controller:

'use strict';
    .controller('xxxxController', function ($scope, xxxxServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "test.pdf";
            var a = document.createElement("a");
   = "display: none";
            xxxxServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
       = fileName;

JS services:

    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;

Java REST Web Services – Spring MVC:

@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<byte[]> getPDF() {
        FileInputStream fileStream;
        try {
            fileStream = new FileInputStream(new File("C:\xxxxx\xxxxxx\test.pdf"));
            byte[] contents = IOUtils.toByteArray(fileStream);
            HttpHeaders headers = new HttpHeaders();
            String filename = "test.pdf";
            headers.setContentDispositionFormData(filename, filename);
            ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
            return response;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        return null;

Method 3

michael’s suggestions works like a charm for me 🙂
If you replace $ with $http.get, remember that the .get method accepts 2 parameters instead of 3… this is where is wasted my time… 😉


$http.get('/getdoc/' + $,     
  .success(function (response) {
     var file = new Blob([(response)], {type: 'application/pdf'});
     var fileURL = URL.createObjectURL(file);
     $scope.content = $sce.trustAsResourceUrl(fileURL);


<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>

Method 4

I faced difficulties using “window.URL” with Opera Browser as it would result to “undefined”. Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

$, data, {responseType: 'arraybuffer'})

function success(data) {
   openPDF(, "myPDFdoc.pdf");

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;

Let me know if it helped! 🙂

Method 5

Adding responseType to the request that is made from angular is indeed the solution, but for me it didn’t work until I’ve set responseType to blob, not to arrayBuffer. The code is self explanatory:

            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
             var blob = new Blob([]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   

Method 6

Most recent answer (for Angular 8+):"your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
  (res) => {

public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
  var file = new Blob([response], {type: 'application/pdf'});
  var fileURL = URL.createObjectURL(file);
  this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);

  HTML :

  <embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />

Method 7

I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.

Most of the questions have the same components, but it took a while to figure out the right order to make it work.

Thank you @Nikolay Melnikov, your comment/reply to this question was what made it work.

In a nutshell, here is my AngularJS Service backend call:

    //Get the download url of the file
    let fullPath = this.paths.downloadServerURL + fileId;
    // return the file as arraybuffer 
    return this.$http.get(fullPath, {
      headers: {
        'Authorization': 'Bearer ' + this.sessionService.getToken()
      responseType: 'arraybuffer'

From my controller:

   myService.getDownloadUrl(idOfTheFile).then( (response) => {
      //Create a new blob object
      let myBlobObject=new Blob([],{ type:'application/pdf'});

      //Ideally the mime type can change based on the file extension
      //let myBlobObject=new Blob([],{ type: mimeType});

      var url = window.URL || window.webkitURL
      var fileURL = url.createObjectURL(myBlobObject);
      var downloadLink = angular.element('<a></a>');
      downloadLink[0].click();//call click function
      url.revokeObjectURL(fileURL);//revoke the object from URL

Method 8

A suggestion of code that I just used in my project using AngularJS v1.7.2

$http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
            .then(function (response) {
                var file = new Blob([], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                $scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);

<embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment