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

Simo D'lo Mafuxwana picture Simo D'lo Mafuxwana · Feb 7, 2014 · Viewed 248.1k times · Source

I have been trying to display pdf file which I am getting as a blob from a $http.post 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.

JS:

According to this doc, I went on and tried...

$http.post('/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.

HTML:

<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.

Answer

michael picture michael · Feb 12, 2014

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:

$http.post('/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>