How do I get a multi-page pdf from a website using jsPDF and HTML2Canvas?

前端 未结 5 1935
生来不讨喜
生来不讨喜 2021-02-19 05:03

I have a script that uses HTML2Canvas to take a screenshot of a div within the page, and then converts it to a pdf using jsPDF.

The problem is the pdf that

5条回答
  •  攒了一身酷
    2021-02-19 05:48

    pdf.addHtml does not work if there are svg images on the web page. I copy the solution here, based on the picture being in a canvas already.

    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 imgData = canvas.toDataURL('image/png');
    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');`
    

提交回复
热议问题