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.

8
  • What browser are you using? Only some browsers support the base64 capability. Here is some more info: Embedding Base64 Commented Jul 8, 2015 at 18:17
  • Hmm, chrome supports a uri up to 2mb, i'm assuming it isn't bigger than that? Data Protocol Size Limits Commented Jul 8, 2015 at 18:33
  • I created a sample Fiddle 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 which may be of interest to you in using a blob instead of a data uri. I updated my Fiddle to show an example of how to implement. Commented Jul 8, 2015 at 19:03
  • @JasonWilczak yes i think it is more than that any work around? Commented Jul 9, 2015 at 3:38
  • the blob doesn't open a pdf either? Commented Jul 9, 2015 at 3:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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, stackoverflow.com/questions/20401006/…
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
@boi_echos I have the same issue as yours. How did you solve it please ?
-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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.