Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Open PDF in new tab from byte array

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

});
like image 671
Jeremy Wagner Avatar asked Jan 28 '15 16:01

Jeremy Wagner


2 Answers

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

like image 58
aniltilanthe Avatar answered Oct 08 '22 01:10

aniltilanthe


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

like image 40
Gonnarule Avatar answered Oct 08 '22 01:10

Gonnarule