【问题标题】:jsPDF multi page PDF with HTML renderer带有 HTML 渲染器的 jsPDF 多页 PDF
【发布时间】:2022-03-08 18:44:49
【问题描述】:

我在我的站点中使用 jsPDF 来生成 PDF。但现在我有多个 DIV 可以打印在一个 PDF 中。这可能需要 2 到 3 页。

例如:

<div id="part1">
  content
</div>

<div id="part2">
  content
</div>

<div id="part2">
   content
</div>

我的 JS 代码

  • 这有效,但不像我预期的那样,它添加了一部分内容(不能包含在多个页面中)。
  • 它会删除 br、h1 等 html 标签。
    function formtoPDF() {
      jsPDF.API.mymethod = function() {
        // 'this' will be ref to internal API object. see jsPDF source
        // , so you can refer to built-in methods like so:
        //   this.line(....)
        //   this.text(....)
      };
      var doc = new jsPDF();
      doc.mymethod();
      var pdfPart1 = jQuery('#genPDFpart1');
      var pdfPart2 = jQuery(".ltinerary");
      var pdfPart3 = jQuery("#domElementHTML");
      var specialElementHandlers = {
        '#loadVar': function(element, renderer) {
          return true;
        }
      };
      doc.fromHTML(pdfPart1.html() + pdfPart3.html() + pdfPart3.html(), 15, 15, {
        'width': 170,
        'elementHandlers': specialElementHandlers
      });
      doc.output('save', 'Download.pdf');
    }

我可以为此提供解决方案吗?提前谢谢朋友们。

【问题讨论】:

  • 大家好,有什么解决办法吗?
  • 单张图片需要拆分成多页怎么办。

标签: multipage jspdf


【解决方案1】:

我有同样的工作问题。在 MrRio github 中搜索我发现了这个:https://github.com/MrRio/jsPDF/issues/101

基本上,在添加新内容之前,您必须始终检查实际页面大小

doc = new jsPdf();
...
pageHeight= doc.internal.pageSize.height;

// Before adding new content
y = 500 // Height position of new content
if (y >= pageHeight)
{
  doc.addPage();
  y = 0 // Restart height position
}
doc.text(x, y, "value");

【讨论】:

  • 你能为此创建一个演示小提琴吗?
  • 我猜你应该以某种方式迭代,直到你的“身高需求”得到满足,如果元素不适合一页,则不仅仅是添加一页(问题确实说内容可能需要 3 页) .但无论如何......根据我的经验,“fromHTML”方法已经处理了新页面的创建,尽管在页面更改中某些内容会丢失 - 这是我试图搜索的问题。
  • 这里的 x 是什么?
  • 好吧,从那以后已经过去了 3 年。通过推论我猜“x”是水平位置
【解决方案2】:

这是一个使用 html2canvas 和 jspdf 的示例,尽管您如何生成画布并不重要——我们只是将其高度用作 for loop 上的断点,其中创建了一个新页面并添加了内容。

在for循环之后,pdf被保存。

function makePDF() {

   var quotes = document.getElementById('container-fluid');
   html2canvas(quotes).then((canvas) => {
        //! MAKE YOUR PDF
        var pdf = new jsPDF('p', 'pt', 'letter');

        for (var i = 0; i <= quotes.clientHeight/980; i++) {
            //! This is all just html2canvas stuff
            var srcImg  = canvas;
            var sX      = 0;
            var sY      = 980*i; // start 980 pixels down for every new page
            var sWidth  = 900;
            var sHeight = 980;
            var dX      = 0;
            var dY      = 0;
            var dWidth  = 900;
            var dHeight = 980;

            window.onePageCanvas = document.createElement("canvas");
            onePageCanvas.setAttribute('width', 900);
            onePageCanvas.setAttribute('height', 980);
            var ctx = onePageCanvas.getContext('2d');
            // details on this usage of this function: 
            // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
            ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);

            // document.body.appendChild(canvas);
            var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);

            var width         = onePageCanvas.width;
            var height        = onePageCanvas.clientHeight;

            //! If we're on anything other than the first page,
            // add another page
            if (i > 0) {
                pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
            }
            //! now we declare that we're working on that page
            pdf.setPage(i+1);
            //! now we add content to that page!
            pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));

        }
        //! after the for loop is finished running, we save the pdf.
        pdf.save('Test.pdf');
  });
}

【讨论】:

  • 你是个了不起的人!我希望我能尽快得到这个答案。
  • 是的,这有帮助。但由于列更多,表格超出了页面宽度,并且某些列变得不可见。我希望表格自动调整大小以适应页面宽度。另外,空格不应该是黑色的,它应该有白色的背景。请帮忙。
  • @ITSagar:查看此答案以更改画布大小:stackoverflow.com/questions/3420975/html5-canvas-zooming |不过,不知道为什么你的空白是黑色的。我在使用此代码时没有发生这种情况,因此您必须解决另一个问题。
  • 对于那些想要页边距的人,我通过我的#content的尺寸var setWidth = 1170; var setHeight = 1514.118;修改了画布的高度和宽度,然后使用addImage参数pdf.addImage(canvasDataURL, 'PNG', 40, 40, (width*.62) - 190, (height*.62) - 90);进行播放
  • 你是个传奇,先生,比你
【解决方案3】:

我在此页面上找到了解决方案:https://github.com/MrRio/jsPDF/issues/434 来自用户:王之轩

我在这里复制解决方案: // 假设你的图片已经在画布中了

      var imgData = canvas.toDataURL('image/png');

      /*
      Here are the numbers (paper width and height) that I found to work. 
      It still creates a little overlap part between the pages, but good enough for me.
      if you can find an official number from jsPDF, use them.
      */
      var imgWidth = 210; 
      var pageHeight = 295;  
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;

      var doc = new jsPDF('p', 'mm');
      var position = 0;

      doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      doc.save( 'file.pdf');

【讨论】:

  • 这是一个完整的例子,用 jsPDF 和 html2canvas 在 pdf 中创建 html 图像:techumber.com/2015/04/… 没有以前的解决方案
  • 谢谢伙计,工作就像一个魅力。只有一件事,如果你使用点击事件,你必须到页面顶部。 window.scrollTo(0, 0);
  • doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, undefined,'FAST'); PDF 大小 90mb 到 3mb,质量很好。
【解决方案4】:
 var doc = new jsPDF('p', 'mm');

 var imgData = canvas.toDataURL('image/png');
 var pageHeight= doc.internal.pageSize.getHeight();
 var pageWidth= doc.internal.pageSize.getWidth();

 var imgheight = $('divName').height() * 25.4 / 96; //px to mm
 var pagecount = Math.ceil(imgheight / pageHeight);

 /* add initial page */
 doc.addPage('l','mm','a4');
 doc.addImage(imgData, 'PNG', 2, 0, pageWidth-4, 0);

 /* add extra pages if the div size is larger than a a4 size */
 if (pagecount > 0) {
     var j = 1;
     while (j != pagecount) {
         doc.addPage('l','mm','a4');
         doc.addImage(imgData, 'PNG', 2, -(j * pageHeight), pageWidth-4, 0);
         j++;
     }
 }

【讨论】:

  • 谢谢它真的有帮助?
  • 我已经有了初始页面。这个初始的“addPage”刚刚为我添加了一个空页面
【解决方案5】:

您可以同时使用html2canvas 插件和jsPDF。处理顺序: html转png & png转pdf

示例代码:

jQuery('#part1').html2canvas({
    onrendered: function( canvas ) {
        var img1 = canvas.toDataURL('image/png');
    }
});
jQuery('#part2').html2canvas({
    onrendered: function( canvas ) {
        var img2 = canvas.toDataURL('image/png');
    }
});
jQuery('#part3').html2canvas({
    onrendered: function( canvas ) {
        var img3 = canvas.toDataURL('image/png');
    }
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page

doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");

【讨论】:

    【解决方案6】:
    $( document ).ready(function() {    
    $('#cmd').click(function() {
          var options = {
                  pagesplit: true //include this in your code
          };
          var pdf = new jsPDF('p', 'pt', 'a4');
          pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
            pdf.save('Menu.pdf');
          });
        });
    });
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    【解决方案7】:

    【讨论】:

      【解决方案8】:

      以下是我的代码,但问题是文档没有拆分以在新页面中显示文档的另一部分。

      请改进此代码。

      <script type='text/javascript'>
      $(document).on("click", "#btnExportToPDF", function () {
          var table1 =
          tableToJson($('#table1')[0]),
          cellWidth =42,
          rowCount = 0,
          cellContents,
          leftMargin = 2,
          topMargin = 12,
          topMarginTable =5,
          headerRowHeight = 13,
          rowHeight = 12,
          l = {
              orientation: 'p',
              unit: 'mm',
              format: 'a3',
              compress: true,
              fontSize: 11,
              lineHeight: 1,
              autoSize: false,
              printHeaders: true
          };
      
          var doc = new jsPDF(l,'pt', 'letter');
      
          doc.setProperties({
              title: 'Test PDF Document',
              subject: 'This is the subject',
              author: 'author',
              keywords: 'generated, javascript, web 2.0, ajax',
              creator: 'author'
          });
          doc.cellInitialize();
      
          $.each(table1, function (i, row)
          {
              rowCount++;
      
              $.each(row, function (j, cellContent) {
      
                  if (rowCount == 1) {
                      doc.margins = 1;
                      doc.setFont("Times New Roman");
                      doc.setFontType("bold");
                      doc.setFontSize(11);
      
                      doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
                  }
                  else if (rowCount == 2) {
      
                      doc.margins = 1;
                      doc.setFont("Times ");
                      doc.setFontType("normal");
                      // or for normal font type use ------ doc.setFontType("normal");
      
                      doc.setFontSize(11);
      
                      doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
                  }
                  else {
      
                      doc.margins = 1;
                      doc.setFont("Times  ");
                      doc.setFontType("normal ");
                      doc.setFontSize(11);
                      doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
                      // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
                  }
              })
          })
          doc.save('sample Report.pdf');
      });
      
      function tableToJson(table) {
      
          var data = [];
      
          // first row needs to be headers
          var headers = [];
      
          for (var i=0; i<table.rows[0].cells.length; i++) {
              headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
          }
      
          // go through cells
          for (var i=1; i<table.rows.length; i++) {
      
              var tableRow = table.rows[i];
      
              var rowData = {};
      
              for (var j=0; j<tableRow.cells.length; j++) {
                  rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
              }
      
              data.push(rowData);
          }
      
          return data;
      }
      </script>
      

      【讨论】:

        【解决方案9】:

        自动不将数据拆分为多页。您可以手动拆分。

        如果您的 ( rowCount * rowHeight ) > 420mm ( A3 Height in mm ) 添加新的页面功能。 (对不起,我无法在没有运行的情况下编辑您的代码) 添加新页面后leftMargin,topMargin = 0; ( 重来 ) 我用你的添加了示例代码。我希望它是正确的。

        else {
            doc.margins = 1;
            doc.setFont("Times  ");
            doc.setFontType("normal ");
            doc.setFontSize(11);
            if ( rowCount * rowHeight > 420 ) {
                doc.addPage();
                rowCount = 3; // skip 1 and 2 above
            } else {
                // now rowcount = 3 ( top of new page for 3 )
                // j is your x axis cell index ( j start from 0 on $.each function ) or you can add cellCount like rowCount and replace with
                // rowcount is your y axis cell index
                left = ( ( j ) * ( cellWidth + leftMargin );
                top = ( ( rowcount - 3 ) * ( rowHeight + topMargin );
                doc.cell( leftMargin, top, cellWidth, rowHeight, cellContent, i);
                // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
            }
        }
        

        您可以直接将html无损转换为pdf。 Youtube video for html => pdf example

        【讨论】:

          【解决方案10】:
                   html2canvas(element[0], {
                              onrendered: function (canvas) {
                                  pages = Math.ceil(element[0].clientHeight / 1450);
                                  for (i = 0; i <= pages; i += 1) {
                                      if (i > 0) {
                                          pdf.addPage();
                                      }
                                      srcImg = canvas;
                                      sX = 0;
                                      sY = 1450 * i;
                                      sWidth = 1100;
                                      sHeight = 1450;
                                      dX = 0;
                                      dY = 0;
                                      dWidth = 1100;
                                      dHeight = 1450;
                                      window.onePageCanvas = document.createElement("canvas");
                                      onePageCanvas.setAttribute('width', 1100);
                                      onePageCanvas.setAttribute('height', 1450);
                                      ctx = onePageCanvas.getContext('2d');
                                      ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
                                      canvasDataURL = onePageCanvas.toDataURL("image/png");
                                      width = onePageCanvas.width;
                                      height = onePageCanvas.clientHeight;
                                      pdf.setPage(i + 1);
                                      pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
                                  }
                                  pdf.save('testfilename.pdf');
                              }
                          });
          

          【讨论】:

            【解决方案11】:
            var a = 0;
            var d;
            var increment;
            
            for(n in array){
                d = a++;        
            
                if(n % 6 === 0 && n != 0){
                    doc.addPage();
                    a = 1;
                    d = 0;
                }
            
                increment = d == 0 ? 10 : 50;
                size = (d * increment) <= 0 ? 10 : d * increment;
            
                doc.text(array[n], 10, size);
            }
            

            【讨论】:

              猜你喜欢
              • 2013-07-03
              • 2012-07-23
              • 1970-01-01
              • 2013-07-31
              • 2015-02-26
              • 1970-01-01
              • 2018-04-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多