问题
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.
回答1:
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.
回答2:
JavaScript code :
=============
jQuery.ajax({
url: site_params.ajaxurl,
type: "POST",
data: total_box_data,
dataType: 'json',
success: function (response) {
div_name.prop("disabled", false);
jQuery('.createpdfdata').text('Create Pdf');
if (response.status == 'failure') {
// show message as per design
//alert(response.error_message);
jQuery('.extra_error_message').html('<div class="alert alert-danger">' + response.error_message + '</div>');
// jQuery('#signup').val('Register');
} else if (response.status == 'success') {
var myBase64 = response.filenamepdf;
var blob;
blob = converBase64toBlob(myBase64, 'application/pdf');
var blobURL = URL.createObjectURL(blob);
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = blobURL;
save.download = response.filenamepdfdata || 'unknown';
save.style = 'display:none;opacity:0;color:transparent;';
(document.body || document.documentElement).appendChild(save);
if (typeof save.click === 'function') {
save.click();
} else {
save.target = '_blank';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
}
(window.URL || window.webkitURL).revokeObjectURL(save.href);
} else if (!!window.ActiveXObject && document.execCommand) { // for IE
var _window = window.open(blobURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, response.filenamepdfdata || blobURL)
_window.close();
}
jQuery('.extra_success_message').html('<div class="alert alert-success alert-dismissible">' + response.success_msg + '</div>');
// jQuery('#signup').val('Register');
} else {
// show error or success message as per design not in alert
//alert('pdf is not generate');
jQuery('.extra_error_message').html('<div class="alert alert-danger">' + response.error_message + '</div>');
}
}
});
function converBase64toBlob(content, contentType) {
contentType = contentType || '';
var sliceSize = 512;
var byteCharacters = window.atob(content); //method which converts base64 to binary
var byteArrays = [
];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {
type: contentType
}); //statement which creates the blob
return blob;
}
Php code :
==========
$html = '';
$html .= '
<h3 class="h3_8">Get in touch with us on:</h3>
<p class="p_3" >
<span class="div3"><img style="margin:3px 3px 0 0; display:inline-block; vertical-align:top;" src="'.get_template_directory_uri().'/images/pdf_locationico.png" alt=""> '.$pdfaddress.'</span>
<span class="div4"><img style="margin:4px 4px 0 24px; display:inline-block; vertical-align:top;" src="'.get_template_directory_uri().'/images/pdf_phoneico.png" alt=""> '.$pdftelephone.'</span> <br>
<span class="div5"><img style="margin:7px 5px 0 0; display:inline-block; vertical-align:top;" src="'.get_template_directory_uri().'/images/pdf_mailico.png" alt=""> '.$pdfmailaddress.'</span>
<span class="div6"><img style="margin:5px 4px 0 24px; display:inline-block; vertical-align:top;" src="'.get_template_directory_uri().'/images/pdf_websiteico.png" alt=""> <a href="'.$pdfsiteurl.'">'.$pdfsitetext.'</a></span>
</p>';
$file_name_pdf = 'digicore_' . time() . '.pdf';
//$newurl = get_bloginfo('template_directory') . '/' . $file_name_pdf;
$newurl = $upload_dir['url'] . '/' . $file_name_pdf;
//$file_name_url = get_template_directory() . '/' . $file_name_pdf;
chmod(get_template_directory(), 0777);
chmod(get_bloginfo('template_directory'), 0777);
chmod($upload_dir['url'],0777);
chmod($upload_dir['path'],0777);
$file_name_url = $upload_dir['path'] . '/' . $file_name_pdf;
$mpdf = new mPDF();
//echo $html;
$mpdf->WriteHTML($html);
$mpdf->useOnlyCoreFonts = true;
$mpdf->SetDisplayMode('fullpage');
//$mpdf->Output($file_name_url, 'I');
$base_64_string =base64_encode($mpdf->Output($file_name_pdf, 'S'));
$resultArr['status'] = 'success';
$resultArr['success_msg'] = __('Your PDF Was Successfully Generated.');
$resultArr['filepath'] = $newurl;
$resultArr['filenamepdf'] = $base_64_string ;
$resultArr['filenamepdfdata'] = $file_name_pdf;
//echo "<pre>";
//print_r($resultArr);
echo json_encode($resultArr);
die();
来源:https://stackoverflow.com/questions/31299799/how-to-open-base64-encoded-pdf-in-javascript