javascripthtmlwkhtmltopdf

wkhtmltopdf: runs js if I pass it a page url but not from a static html file


I'm using a native javascript plugin to highlight some text in a web page.

If I pass wkhtmltopdf the url of the page then the highlighting comes through in the resulting pdf.

However, if I render out the page to an html file first, and then pass that html file to wk, then it doesn't run the js and I don't get the highlighting.

Is there a way around this? I could run it again against the url, but it would mean a double-request to the website which isn't very efficient.

My version is wkhtmltopdf 0.12.6 (with patched qt)

This is the js I have in my html:

      <script src="/javascripts/mark_highlighter/dist/mark.js"/>
      <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function(e) {

          var instance = new Mark(document.querySelector(".doc__page"));
          //can take an array of strings or a single string
          instance.mark(<%= params[:highlighted].inspect %>, {
            separateWordSearch: false
            ,accuracy: "exactly"
          });
        });
      </script>

Solution

  • With the scripts being embedded using relative URLs, wkhtmltopdf is likely to have problems "finding" them, in the context of an HTML document being passed.

    /javascripts/mark_highlighter/dist/mark.js is probably taken as a path from the file system root (at least on a Linux system) - but the files are likely not located there. In the HTTP context, this maps to the document root instead.