简体   繁体   中英

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

});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM