Damian Morris
Damian Morris

Reputation: 61

How can I dynamically add page breaks in jspdf, to prevent tables from breaking across two pages?

I am trying to create a web page that exports database information into a PDF, with tables that pull from a database with PHP and MySQL.

My tables have variable length, and can at times include more than one table, potentially up to 3+ tables.

In the case that the initial table would take up a large amount of space on a page, that the second table would break across to subsequent pages, how would I tell jspdf to go back to previous <table> tag, and insert a -page break- before it? (i.e. if any row of table 2+ would break and move to the next page, move the entire table to the next page).

I've considered trying to crawl and count the <tr> tags to get a count, and trying to set an if-else statement to send the table to the next page, but I don't know how that would work for more than two tables.

<script>
  //this my current idea of the code, none of it is implemented or tested
  $(document).on('load', function(e) { //when the pages loads, execute this function
    var PDF_WIDTH = 816;
    var PDF_HEIGHT = (PDF_Width * 1.2941); //for a 8.5*11 Letter sized pdf
    var rowCount = 0;
    var tableCount = 0;

    $(tr).each(function(e) { //counts all the rows that exists on the page
      var rowCount++;
    });

    $(table).each(function(e) { //counts all the tables that exist on the page
      var tableCount++;
    });

    if (rowcount > 36) { //if the total number of rows would exceed the amount of rows displayed on the page
      var pdf = new jsPDF('p', 'pt' [PDF_WIDTH, PDF_HEIGHT]);
      //??? trying to select the table that would break 
      //??? add a page break before the second table
      //alternatively append a page break after the first table
    }
  });
</script>

Upvotes: 3

Views: 16482

Answers (2)

Monika Tamsoy
Monika Tamsoy

Reputation: 9

I was in the same situation. Set 'rowPageBreak' option to 'avoid' and

  • The table splits
  • A new page is added
  • The extra rows flows to the new page

Upvotes: 0

nbk
nbk

Reputation: 49375

you should try jspdf autotable plugin. https://github.com/simonbengtsson/jsPDF-AutoTable and look at the examples for multiple tables

Upvotes: 2

Related Questions