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 an empty pdf when I open the pdf. My answer is the result of the output stream from spring mvc
Please, help.
+3
source to share
1 answer
For Chrome and Firefox, you can simply use the base64 data directly on the 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 an 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 check out the Javascript behind this page http://www.cloudformatter.com/css2pdf which is a PDF formatting service. Chrome and Firefox can be embedded in the page or displayed in a new window, IE does not support base64 in the object (or any other), so this code triggers the download.
+7
source to share