jsPDF multi page PDF with HTML renderer

前端 未结 11 1665
感情败类
感情败类 2020-11-27 13:54

I am using jsPDF in my site to generate PDFs. But now I have multiple DIVs to print in a single PDF. which may take 2 to 3 pages.

For example:



        
11条回答
  •  北海茫月
    2020-11-27 14:42

    I found the solution on this page: https://github.com/MrRio/jsPDF/issues/434 From the user: wangzhixuan

    I copy the solution here: // suppose your picture is already in a canvas

          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');
    

提交回复
热议问题