25

I'm using AngularJS with an HTTP resource to call an external API and my response is a byte array. I need to turn this byte array into a PDF in a new window. I haven't seen any very good solutions on here that work cross browser or that are pure javascript. Is there a way to do this?

Here is my code:

Javascript

Document.preview({id: $scope.order.id}, function(data){

    // Open PDF Here
    var file = new Blob([data], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);

});
Jeremy Wagner
  • 485
  • 4
  • 9
  • 19
  • http://mozilla.github.io/pdf.js have some good reference here – AAH-Shoot Jan 28 '15 at 16:24
  • I've been looking at that, but I don't see any good examples using a byte array. I've also been looking at http://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app but I'm just getting an error "Failed to load PDF Document" – Jeremy Wagner Jan 28 '15 at 16:32
  • Are there any proprietary plugins or anything to do this? Several pages open pdf's, how can I? – Jeremy Wagner Jan 29 '15 at 15:29

2 Answers2

25

You would need to pass the responseType in your service call

$http.post('/Service-URL', dataTO, {responseType: 'arraybuffer'});

then in the success of your data call this should open up pdf in a new window:-

    getDocument()
        .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL);
    })

From this answer :- https://stackoverflow.com/a/21730535/3645957 by https://stackoverflow.com/users/2688545/michael

aniltilanthe
  • 4,587
  • 1
  • 18
  • 17
  • 1
    @ihodonald It is an Optional attribute 'name'. It was a typo in the answer. But it is optional, so not necessary. like from here https://www.w3schools.com/jsref/met_win_open.asp -> i removed it from the answer. – aniltilanthe Jan 06 '20 at 15:31
  • 1
    Dude, this thing: {responseType: 'arraybuffer'} save my life. Thank you very much! – Sérgio Danilo Jan 23 '21 at 18:08
18

If anyone still looks for that, here is what I'm doing (and working) :

var pdfAsDataUri = "data:application/pdf;base64,"+byteArray;
window.open(pdfAsDataUri);

Where byteArray is the data you receive. It's maybe not a nice solution (byte array is visible in the URL), but it works...

Gonnarule
  • 350
  • 2
  • 7