使用 domtoimage.toPng 为 pdf 页面内的两个 div 导出 pdf

问题描述

我有两个 div (div1,div2) 我想在 pdf 页面 1 中导出 div1 并在 pdf 页面 2 中导出 div2 我的问题我只能使用 domtoimage.toPng 从它们捕获一个 div 我怎样才能捕获我的两个 div代码:`

                               <script>
              $('#downloadPDF').click(function () {
              domtoimage.toPng(document.getElementById('div1'))
          //  domtoimage.toJpeg(document.getElementById('div2'))

    .then(function (blob) {
        var pdf = new jsPDF('p','pt',[$('#div1').width(),$('#div1').height()]);
        pdf.addImage(blob,'PNG',$('#div2').width(),$('#div2').height());

  pdf.addPage();

        pdf.addImage(blob,$('#div1').width(),$('#div1').height());
        pdf.save("report.pdf");

        that.options.api.optionsChanged();
    });
    });
    </script>`

解决方法

您需要准备 2 个 blob 才能将它们保存为 PDF。

$('#downloadPDF').click(function() {
  Promise.all([
      domtoimage.toPng(document.getElementById('div1')),domtoimage.toPng(document.getElementById('div2'))
    ])
    .then(function([blob1,blob2]) {
      var pdf = new jsPDF('p','pt',[$('#div1').width(),$('#div1').height()]);
      pdf.addImage(blob1,'PNG',$('#div1').width(),$('#div1').height());

      pdf.addPage();

      pdf.addImage(blob2,$('#div2').width(),$('#div2').height());
      pdf.save("report.pdf");

      that.options.api.optionsChanged();
    });
});