How to open base64 encoded pdf in javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); |
打开PDF时,我会得到一个空白的PDF。我的回答是来自SpringMVC的输出流结果
请帮忙。
对于chrome和firefox,您可以直接在对象标签上使用base64数据:
1 2 3 4 5 6 7 8 | 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>'); |
然后要么添加到现有页面,要么打开一个新窗口:
1 2 3 4 5 6 | 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); |
您可以检查此页面后面的javascript http://www.cloudformatter.com/css2pdf,这是一个PDF格式服务。chrome和firefox可以嵌入页面或显示在一个新窗口中,即不支持对象中的base64(或其他任何东西),因此此代码触发下载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | 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('' + response.error_message + ''); // 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('' + response.success_msg + ''); // 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('' + response.error_message + ''); } } }); 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: <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> <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=""> '.$pdfsitetext.'</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"[cc lang="javascript"]"; //print_r($resultArr); echo json_encode($resultArr); die(); |