如何避免大型HTML表格中文本的分页符(打印/ PDF)?

时间:2017-07-03 20:01:13

标签: javascript html css pdf page-break

我有以下单个HTML文件(包括样式/脚本):FQ.html

我有以下问题: lame page breaks

我已经迭代了解决方案尝试,最新的尝试有以下一些CSS ......

@media print{
  @page {
    size:1080px 1080px;
    margin: 0px;
  }
  .page-break-before  { page-break-before: always; display:block; width:200%;}
  .page-break  { display:block; page-break-after: always; width:200%; }
}

...和Javascript。

//set viewport height in print mode.
var height = 780;  //screen.height;
//pick up the total table.
var table = $('#identification_section > table')[0];
//initialize the sum variable with height of title (h2 tag)
var sum = 24;
//loop all table rows including child tables 
for (var i = 0, row; row = table.rows[i]; i++) {
  //tr is the parent table row which may contain child table.
  var tr = row;
  if (tr.offsetHeight > height) {  //if row's hight is bigger than viewport height, it contains child table.
    var child_table = tr.cells[0].children[0]; 
    if (child_table.className=="group-table") {  //pick up child table.
      var child_sum = 0;
      for (var j=0, subrow; subrow = child_table.rows[j]; j++) {
        var subtr = subrow;  //pick up child table's row
        child_sum += subtr.offsetHeight; // sum up the row's height.
        if (child_table.rows[j+1]!=null) //check if next row is existing, not end row.
          if (child_sum + child_table.rows[j+1].offsetHeight > height) {  // if (sum of table rows so far + next row's height) > viewport height
            //var temp = subtr.cells[0]; // pick up the first cell of row
            child_table.rows[j+1].classList.add('page-break-before'); // set the page-break-before to next row.
            subtr.classList.add('page-break'); // set the page-break to current row
            child_sum = 0; // set the sum 0 for next page calculation.
          }
      }
    }
  }

  sum += tr.offsetHeight; // sum up the height of parent rows.
  //tr.cells[0].setAttribute('style', 'height:'+tr.offsetHeight+'px');
  if (table.rows[i+1]!=null) // check if there is next row.
    if (sum + table.rows[i+1].offsetHeight>height) {  // if sum + next row'height is bigger than viewport row
      //var temp = tr.cells[0];
      table.rows[i+1].classList.add('page-break-before'); //set the page-break-before class to next row
      tr.classList.add('page-break'); // set the page-break class to current row
      sum = 0; //set the sum 0 for next page calculation.
    }
}

然而,我仍然不知所措。我没有试图避免打破文本,而是觉得避免破坏文本会更容易。尽管如此,我尝试过的解决方案仍有2个或更多问题。一个是休息时间太过分了,第二个是某些部分的宽度设置为50%。

防止文本或文本中断,最好是文本。

1 个答案:

答案 0 :(得分:0)

您必须将page-break-beforepage-break-after规则应用于文档中的所有元素。

例如,对于表格,您可以使用table tr和类似的选择器。