Skip to content

Html function renders extra page when using provided pdf dimensions #3997

Description

@charlesg99

When using "px" as the pdf unit and rendering a multi page html element sized according to the provided pageSize, the html element seems to correctly fill the pdf pages, but an extra blank page is added at the end of the pdf. Using doc.internal.pageSize.getHeight() returns a decimal value (1122.52 for a4, scale 1), so trying to floor that value removes the extra blank page, but the last page is also truncated by (number of pages * .52) pixels.

The doc.internal.pageSize.getHeight() value seems pixel perfect, no matter how many pages are rendered, the html element never bleeds out on that last extra blank page, so why is this blank page there at all? Probably a crazy precision problem that should be handled somehow.

Here is a simple repro that should produce a 10 pages pdf, but ends up with 11:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<body>
  <script src="https://unpkg.com/html2canvas@latest/dist/html2canvas.min.js"></script>
  <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
  <script>
    function createDoc(floor) {
      let doc = new window.jspdf.jsPDF({
        orientation: 'p',
        unit: 'px',
        format: 'a4',
        // hotfixes: ['px_scaling'], // not helping
      })

      let pageNum = 10
      let pageHeight = doc.internal.pageSize.getHeight()
      let el = document.createElement('div')
      
      if (floor)
        pageHeight = Math.floor(pageHeight)

      el.style.height = `${pageHeight * pageNum}px`
      el.style.width = `${doc.internal.pageSize.getWidth()}px`
      el.style.backgroundColor = '#00f'

      doc.html(el, {
        callback: (doc) => {
          window.open(doc.output('bloburl'))
        },
        margin: [0, 0, 0, 0],
        html2canvas: {
          logging: false,
          scale: 1,
        },
      })
    }
  </script>
  <br/>
  <button onclick="createDoc()">getHeight as is</button>
  <br/><br/>
  <button onclick="createDoc(true)">getHeight floor</button>
</body>
</html>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions