27

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);

});
3
  • mozilla.github.io/pdf.js have some good reference here Commented Jan 28, 2015 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 stackoverflow.com/questions/21628378/… but I'm just getting an error "Failed to load PDF Document" Commented Jan 28, 2015 at 16:32
  • Are there any proprietary plugins or anything to do this? Several pages open pdf's, how can I? Commented Jan 29, 2015 at 15:29

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

2 Comments

@ihodonald It is an Optional attribute 'name'. It was a typo in the answer. But it is optional, so not necessary. like from here w3schools.com/jsref/met_win_open.asp -> i removed it from the answer.
Dude, this thing: {responseType: 'arraybuffer'} save my life. Thank you very much! 😊
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...

4 Comments

Data URI's don't work on all browsers. Especially even recent versions of IE.
now chrome v60 not allowing to open file from byteArray using window.open , it has depreciated in chrome v60
tried with v94 and it worked
Nice. works with Chrome 108 version. I need to quickly verify a bytearray and this method is useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.