Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open base64 encoded pdf in javascript

var ajaxSettings = {
            url: urls.orders.list+"/"+singlePacket.requests[0].order_id+"/labels", //request labels the status will change to ShipperAssigned
            type: "GET",
            contentType: "application/json",
            headers: { "Authorization": "Bearer " + api.access_token },
            success: function (resp) {
                if (resp != null) {
                    var d = btoa(unescape(encodeURIComponent(resp)));
                    console.log(d);
                    if(d != null)
                    window.open('data:application/pdf;base64, ' + d);
                }

            },
            error: function (jqXhr, textstatus, errorThrown) {
                console.log("Status: " + jqXhr.status + ": error thrown in downloadLabels: " + errorThrown);
                hide_shipping_progress_modal();
            }
        };
        $.ajax(ajaxSettings);

I get a blank pdf when i open the pdf. My response is an outputstream result from spring mvc

Please help.

like image 540
vini Avatar asked Mar 16 '23 11:03

vini


1 Answers

For Chrome and Firefox, you could just use the base64 data directly on an object tag:

    var objbuilder = '';
    objbuilder += ('<object width="100%" height="100%"      data="data:application/pdf;base64,');
    objbuilder += (base64PDF);
    objbuilder += ('" type="application/pdf" class="internal">');
    objbuilder += ('<embed src="data:application/pdf;base64,');
    objbuilder += (base64PDF);
    objbuilder += ('" type="application/pdf" />');
    objbuilder += ('</object>');

Then either add to the existing page or open a new window:

var win = window.open("","_blank","titlebar=yes");
        win.document.title = "My Title";
        win.document.write('<html><body>');
        win.document.write(objbuilder);
        win.document.write('</body></html>');
        layer = jQuery(win.document);

You can examine the Javascript behind this page http://www.cloudformatter.com/css2pdf which is a PDF formatting service. Chrome and Firefox can be embedded in page or displayed in a new window, IE does not support base64 in object (or aanything else) so this code triggers a download.

like image 190
Kevin Brown Avatar answered Mar 25 '23 08:03

Kevin Brown