Html导出PDF,根据页面中空白间隙自动分页

时间:2022-09-07 22:19:44
//首页,下载扩展后的jspdf: http://workshop.red/lib/jspdf.debug.js
//其次,利用html2canvas将html绘制到canvas中
   //最后,执行以下代码
var leftHeight = canvas.height;
var position = 0
var a4Width = 595.28
var a4Height = 841.89
var a4HeightRef = Math.floor(canvas.width/a4Width*a4Height);
var pageData = canvas.toDataURL('image/jpeg', 1.0)
var pdf = new jsPDF('x', 'pt', 'a4')
var index = 0, canvas1 = document.createElement('canvas'), height;

pdf.setDisplayMode('fullwidth','continuous','FullScreen')
$('body').append($(
  '<div class="pdfTip">' +
  ' <div>正在生成第<span class="pdfProgress">1</span>页,共<span class="pdfTotal"></span>页...' +
  '</div>'));

function createImpl(canvas){
  if (leftHeight > 0) {
    index ++;

    var checkCount = 0;
    if(leftHeight > a4HeightRef){
      var i = position + a4HeightRef;
      for (i = position+a4HeightRef; i >= position; i--) {
        var isWrite = true  for (var j = 0; j < canvas.width; j++) {
          var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data   if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
            isWrite = false  break  }
        }
        if (isWrite) {
          checkCount++
          if (checkCount >= 10) {
            break  }
        }
        else {
          checkCount = 0
        }
      }
      height = Math.round(i-position) || Math.min(leftHeight,a4HeightRef);
    }else{
      height = leftHeight;
    }

    canvas1.width = canvas.width;
    canvas1.height = height;

    console.log(index,'height:',height,'pos',position);

    var ctx = canvas1.getContext('2d');
    ctx.drawImage(canvas,0,position,canvas.width,height,0,0,canvas.width,height);

    var pageHeight = Math.round(a4Width/canvas.width*height);
    pdf.setPageSize(null,pageHeight)
    pdf.addPage();
    pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4Width, a4Width/canvas1.width*height)
    leftHeight -= height;
    position += height

    $('.pdfProgress').text(index+1);
    $('.pdfTotal').text(index+Math.ceil(leftHeight/a4HeightRef))
    if(leftHeight>0){
      setTimeout(createImpl,500,canvas);
    }else{
      pdf.save('诊断报告.pdf')
      $('.pdfTip').hide();
    }
  }
}

//当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < a4HeightRef) {
  pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width/canvas.width*leftHeight);
  pdf.save('诊断报告.pdf')
}
else {
  try{
    pdf.deletePage(0);
    $('.pdfTip').show();
    $('.pdfTotal').text(index+Math.ceil(leftHeight/a4HeightRef));
    setTimeout(createImpl,500,canvas);
  }catch (err){
    console.log(err);
  }
}

//文章出处: 红作坊 http://workshop.red

//前端拾色工具: http://www.workshop.red/projects/local/local?color

//前端测量工具:http://www.workshop.red/projects/local/local?ruler

//前端免费项目管理工具: http://www.workshop.red/projects