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

vini
  • 4,657
  • 24
  • 82
  • 170
  • What browser are you using? Only some browsers support the base64 capability. Here is some more info: [Embedding Base64](http://stackoverflow.com/questions/1207190/embedding-base64-images) – JasonWilczak Jul 08 '15 at 18:17
  • Hmm, chrome supports a uri up to 2mb, i'm assuming it isn't bigger than that? [Data Protocol Size Limits](http://stackoverflow.com/questions/695151/data-protocol-url-size-limitations) – JasonWilczak Jul 08 '15 at 18:33
  • I created a sample [Fiddle](http://jsfiddle.net/jasonwilczak/n83rvwn9/1/) to illustrate your issue. The fiddle seems to have the same problem as you. I did come across this post [Creating a Blob from a base64 string in JavaScript](http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript) which may be of interest to you in using a blob instead of a data uri. I updated my [Fiddle](http://jsfiddle.net/jasonwilczak/n83rvwn9/2/) to show an example of how to implement. – JasonWilczak Jul 08 '15 at 19:03
  • @JasonWilczak yes i think it is more than that any work around? – vini Jul 09 '15 at 03:38
  • the blob doesn't open a pdf either? – vini Jul 09 '15 at 03:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82770/discussion-between-vini-and-jasonwilczak). – vini Jul 09 '15 at 04:29
  • Unfortunately, I cannot utilize chat right now. Are you getting any error messages in the console or network trace? – JasonWilczak Jul 09 '15 at 12:56
  • I think there is some issue with my base64 – vini Jul 10 '15 at 05:05

2 Answers2

8

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.

Kevin Brown
  • 8,805
  • 2
  • 20
  • 38
  • Thanks for the answer!. But I don't think it works for IE. It won't trigger a download dialog. For IE, I guess we need to do form POST and return stream to browser, http://stackoverflow.com/questions/20401006/show-a-pdf-stream-in-a-new-window – mlg Jan 05 '16 at 16:22
  • 1
    i used this solution but it doesnt work on SOME pdf files, i usually encounter this on large pdf files but not all. Some big pdfs works with this solution,. id ont know why – Alex Coroza Feb 27 '18 at 08:57
  • @boi_echos I have the same issue as yours. How did you solve it please ? – Zied Hf Jan 31 '19 at 08:53
-1
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();
Maulik patel
  • 2,546
  • 2
  • 20
  • 26