HTML to PDF with Delayed & Asynchronous JavaScript

One of the most common documents generated by DocRaptor is a report, and what’s a report without an eye-catching chart or two? We’ve long supported charting libraries, like HighCharts, but today we’re taking another big (yet surprisingly simple) step forward with our HTML to PDF engine.

Modern JavaScript involves fetching assets asynchronously, filling in data as it arrives, and doing post-render transformations as needed by the page. Even simple web pages are starting to feel more like applications, and historically that has been a problem for our JavaScript engine. When your page is loading or executing scripts after loading, or has a function waiting to execute in the background, it can be difficult to determine what constitutes “finished rendering”.

We’ve decided to take the simplest approach to the problem, and put the choice in the hands of our users. Now you can define a simple function called docraptorJavaScriptFinished(), that returns true if your page has finished rendering, or false otherwise. Any other return value is considered an error. This new function enables a much wider variety of charting/graphing libraries, JavaScript frameworks, and all sorts of new capabilities.

It’s more fun with an example, here’s one straight from our tests:

var didWait = false;
// DocRaptor polls docraptorJavaScriptFinished until it is true
docraptorJavaScriptFinished = function() {
  if (! didWait) {
      didWait = true;
    }, 10000);
    return false;
  document.body.appendChild(document.createTextNode("JavaScript Inserted This Content"));
  return true;

In a real-world example, you might set didWait to true in your actual rendering function, or write the body of your docraptorJavaScriptFinished function more like this:

docraptorJavaScriptFinished = function() {
  return document.getElementById("anAsyncChart") != null;

Because the function is called in the context of your page, you can use all of your usual tools, like jQuery or Underscore, to determine if DocRaptor should move on to PDF rendering.

How will you use JavaScript to make richer, more beautiful documents with DocRaptor? Let us know at @Doc_Raptor!