How to get page width and height in pixels in JavaScript when using wkhtmltopdf

Viewed 958

I am doing the following to generate a PDF from HTML:

wkhtmltopdf --grayscale --page-height 10in --page-width 8in index.html index.pdf

I have this HTML structure:

<html>
  <head>
    <meta charset="utf-8">
    <style>
      .page {
        page-break-after: always;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div class='page'>asdf</div>
    <div class='page'>hkl</div>
    <script>
      window.addEventListener('load', function(){
        var p = document.querySelector('.page')

        var W = p.offsetWidth
        var H = p.offsetHeight
        
        document.body.innerHTML = 'W:' + W + 'H:' + H
      })
    </script>
  </body>
</html>

I am essentially trying to find a way to measure the dimensions of a "page" (not the body or some regular element). So I've added 2 pages so I can make sure that the page-break-after CSS property hopefully takes effect. The final output (if you comment out the document.body.innerHTML = ... part) looks like it's divided into pages. But when I log it like the above example shows (super hacky, don't know how to console.log in wkhtmltopdf), it says:

W:0 H:0

Why does it say that? How do I get the measurements of a generic "page"? I would like to get the page dimensions so I can calculate the number of characters that can fit on a line given a font size, or the number of lines that can fit on a page given line height. But I can't do that without first knowing how to get the page dimensions.

0 Answers
Related