'How to find exact length of pixel in mm

I am using an HTML, CSS, js template, and converting it to pdf with the android app. I had a problem detecting when will next page break so I can put an element on the next page and change its design. I am trying with calculating the distance from the top of the page to the bottom of that element, and then check if that element ends after the page ends.

<script>
  const pageHeight = 275;            //page height without margins in mm
  const pixelSize = 0.2645833333;    //pixel size in mm
  const normalGraph = document.getElementById("normal-graph-block");
  const breakGraph = document.getElementById("break-graph-block");
  const pixelRatio = window.devicePixelRatio;

  function myFunction() {
    //Get distance from top of page to top of element  plus element height
    //multiplyed by pixel size to get distance in mm
    const graphBottomPos = 
      (normalGraph.getBoundingClientRect().top + normalGraph.offsetHeight) * pixelSize;
    if ( graphBottomPos > pageHeight ) {
      normalGraph.style.display = "none";
      breakGraph.style.display = "block";
    }
  }

  window.onload = myFunction;
</script>

It's not working well and I get different values on different phones. I think I need to use devicePixelRatio to compensate for that but I could make it work, even with it.

Please don't tell me to use page-break-before, after.., because I need to hide that element after a page break and show a similar one with a different style.

It would be much better if I could detect that page break somehow, but since it is not <br> element, i think that is not possibile.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source