简体   繁体   中英

jspdf convert html to pdf with multiple pages

I'm using jsPdf and html2pdf to convert html to a pdf file.

I can convert the html fine and download the file but if the html is too big to fit onto a single page, it does not create the other page(s), how do I do this?

code is:

 var pdf = new jsPDF('l', 'pt', 'a4');
 pdf.canvas.height = 72 * 11;
 pdf.canvas.width = 72 * 8.5;
 html2pdf(document.getElementById(id), pdf, function(pdf){
     pdf.save('file.pdf');
 });

Another Solution.

var pdf = new jsPDF('p', 'pt', 'a4');
var options = {
     pagesplit: true
};

pdf.addHTML($(".pdf-wrapper"), options, function()
{
pdf.save("test.pdf");
});

Source : jsPDF multi page PDF with HTML renderrer

another answer : jsPDF multi page PDF with HTML renderrer

If above answer does not work i have done it like this :

download and include in order :

  1. Jquery
  2. html2canvas
  3. jspdf

google them they are easy to find. then have your printable code in a div wrapper report. and call the function with print button. for example (In jsfiddle code will not work because it does not allow external code from non cdn sites but it will work on server)

$(document).ready(function() {
   var form = $('#report');
   var cache_width = form.width();
   var a4 = [595.28, 841.89];


   $('#create_pdf').on('click', function() {
     $('body').scrollTop(0);
     createPDF();
   });

   //create pdf
   function createPDF() {
     getCanvas().then(function(canvas) {
       var imgWidth = 200;
       var pageHeight = 290;
       var imgHeight = canvas.height * imgWidth / canvas.width;
       var heightLeft = imgHeight;
       var doc = new jsPDF('p', 'mm');
       var position = 0;

       var img = canvas.toDataURL("image/jpeg");




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



   while (heightLeft >= 0) {
     position = heightLeft - imgHeight;
     doc.addPage();
     doc.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);
     heightLeft -= pageHeight;
   }


   doc.save('Report.pdf');
   form.width(cache_width);
  });
 }


 // create canvas object
   function getCanvas() {
     form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
     return html2canvas(form, {
       imageTimeout: 2000,
       removeContainer: false
     });
   }

});

https://jsfiddle.net/vnfts73o/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM