UP | HOME

Print a PDF content automatically

The most popular approach of printing out content on an HTML page is calling window.print() directly from the web application.

This works, however, the printed content sometimes has some problems, for example, texts are being cut off, images not printed properly, for most of the time, you can fix it by CSS (using media queries), but even CSS are not the same across browsers. Different browsers will print your content differently.

One good way to reduce the printing problems is using PDF format. You'll generate the PDF on the server side, so you have full control of the layouts, fonts, size,… users will get the same result.

But you'll have limited control for PDF content, this led to some other problems, for example, you want the PDF file to be printed automatically instead of opening it in a new tab and the user have to press Cmd + P manually.

You can solve this problem by embed the PDF content in an iframe, then print it programmatically:

$('<iframe type="application/pdf" src="'+src+'"></iframe>')
  .appendTo(document.body)
  .load(function() {
    setTimeout(function() {
      this.contentWindow.print();
    }.bind(this), 0);
  });

You might want to wait for the PDF file to be fully loaded as well, before printing, this is how Lucid Chart solves the problem:

function download(src){
  $('iframe').remove();
  $.ajax({
    type: 'GET',
    url: src,
    error: function (xhr, ajaxOptions, thrownError) {
      window.parent.postMessage('error', '*');
    },
    xhr: function () {
      var xhr = new window.XMLHttpRequest();
      //Download progress
      xhr.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
          var percentComplete = evt.loaded / evt.total;
          window.parent.postMessage("Printing: " + Math.round(percentComplete*100) + "%", '*');
          // progressElem.html(Math.round(percentComplete * 100) + "%");
        } else {
        }
      }, false);
      return xhr;
    },
    success: function () {
      window.parent.postMessage('done', '*');
      $('<iframe type="application/pdf" src="'+src+'"></iframe>').appendTo(document.body).load(function() {
        setTimeout(function() {
          this.contentWindow.print();
        }.bind(this), 0);
      });
    }
  });
}

$(document).ready(function(){
  window.addEventListener("message", function(e){
    if(e.data.indexOf('https://') == 0){
      download(e.data);
    }
  }, false);
});

Date: 2019-01-17 Thu 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41