1

I am doing a small project with jsPDF. I need to write colored text, changing the font size and using bold text. Therefore fromHtml is my choise, because i can easyly do it with css and html.

The problem is that only around the half of the page can be used to write with fromHtml. If it try to write beyond it a new page is created and the text is wirtten there.

Here a small html example with the javascript code, that can be run on it´s own.

<!DOCTYPE html>
<html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>

<script type="text/javascript">
  function fromHtmlTest() {
    var doc = new jsPDF({
      orientation: 'l',
      unit: 'px',
      format: [30, 30]
    });

    // doc.setFontSize(1); // the workaround for this problem

    var toWrite = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th"];

    for (var i = 0; i < toWrite.length; i++) {
      doc.fromHTML(
        '<div style="font-size:1">' + toWrite[i] + '</div>'
        , 1 // x
        , i // y
        , {
          'width': 10,
          'elementHandlers': {}
        }
      )
    }
    doc.save('Test.pdf');
  }
</script>

<body>
  <input type="button" value="Start" onclick="fromHtmlTest()" />
</body>

Here an immage of the pdf after running the code:

fromHtml example - code result

fromHtml example - code result

"8th" should be directly under "7th" and not at the next page. If "9th" would be added to the array another page would also be added.

How can i use the whole page with fromHtml?

Edit: As workaround "doc.setFontSize(1);" does the trick. I have added it to the example code as a comment.

Daniel
  • 11
  • 2
  • After some rest and going at this problem again i made some more tests. I have found the reason and a workaround for this problem. The background of this problem is that fromHTML does not give the css front-size to the document itself. Therefore when placing "8th" the code checks if there is space at the page, but if the interal document size is not the "1" like it is in the css the next page is choosen. As workaround "doc.setFontSize(1);" does the trick. I have added it to the example code as a comment. – Daniel Mar 17 '20 at 13:13

0 Answers0