title: PhantomJS PDF page break
body: <p>I create a PDF report with header generated automatically by phantomjs. In the report I have a long div which contains text, blank lines, simple data tables etc.
  Since I believe phantomjs might have problem with the page break, I calculate the page break manually, break up the long div into multiple divs with page break at the end of each div.</p>
  
  <p>Here is my calculation in the jQuery(document).ready()</p>
  
  <pre><code>//pagination the Notes pages
  if (encData.pnotes &amp;&amp; encData.pnotes.length &gt; 0) {
  pageCnt++;
  var $notes = jQuery('&lt;div id="pageNotes" class="notes" style="width:100%;margin-top:100px;border:1px solid red"&gt;' + 
    pNotesString + '&lt;/div&gt;');
  $body.append($notes);
  var height = 0;
  var children = $notes.children();
  var p = children.slice(0);
  var pages = [];
  var counter = 0;
  for (var i = 0; i &lt; children.length; i++) {
    if (height + children[i].offsetHeight &lt; 1350)
      height += children[i].offsetHeight;
    else {
      pages.push([counter, i]);
      height = 0;
      counter = i;
    }
  } 
  pages.push([counter, children.length]);
  for (var i = 0; i &lt; pages.length; i++) {
    //first notes page
    if (i == 0) {
      $notes.children().slice(pages[i][1]).remove();
      $notes.after('&lt;div style="border:1px solid black;height:1px"&gt;&lt;/div&gt;&lt;div id="pageNotesBreak" style="page-break-after:always"&gt;&amp;nbsp;&lt;/div&gt;');
    } 
    else {
      pageCnt++;
      var $new = jQuery('&lt;div id="page' + pageCnt + '" class="notes" style="width:100%;margin-top:100px;border:1px solid blue"&gt;&lt;/div&gt;');
      $new.append(p.slice(pages[i][0], pages[i][1]));
      $body.append($new);
      $body.append('&lt;div style="border:1px solid black;height:1px"&gt;&lt;/div&gt;&lt;div id="pageBreak' + pageCnt + '" style="page-break-after:always"&gt;&amp;nbsp;&lt;/div&gt;');
    }
  }
  </code></pre>
  
  <p>The <code>"&lt;div style='border:1px solid black;height:1px'&gt;"</code> is just a silly marker to find where my page breaks are on the PDF.
  1350px in the estimated height of objects where the page break should be created when I traverse all the children of the long div.</p>
  
  <p>In Chrome, I see that I have a total of 5 pages.
  But when it is rendered in PDF, the number of pages goes up to 6 or 7 depending the size of the font, the line height, etc.</p>
  
  <p>Here is the image of the pages</p>
  
  <p><a href="https://i.stack.imgur.com/ve4gd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ve4gd.png" alt="div content runs over header"></a></p>
  
  <p>Does anyone know the cause of the problem? And how to solve it in general.</p>