简体   繁体   English

jspdf将具有多个页面的html转换为pdf

[英]jspdf convert html to pdf with multiple pages

I'm using jsPdf and html2pdf to convert html to a pdf file. 我正在使用jsPdf和html2pdf将html转换为pdf文件。

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? 我可以很好地转换html并下载文件,但是如果html太大而无法放在单个页面上,则它不会创建其他页面,我该怎么做?

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 来源: 带有HTML渲染器的jsPDF多页PDF

another answer : jsPDF multi page PDF with HTML renderrer 另一个答案: 具有HTML渲染器的jsPDF多页PDF

If above answer does not work i have done it like this : 如果以上答案不起作用,我已经这样做了:

download and include in order : 下载并按顺序包括:

  1. Jquery jQuery的
  2. html2canvas html2canvas
  3. jspdf jspdf

google them they are easy to find. 谷歌他们很容易找到。 then have your printable code in a div wrapper report. 然后将可打印代码包含在div包装器报告中。 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) 例如(在jsfiddle中,代码将无法工作,因为它不允许来自非CDN站点的外部代码,但可以在服务器上运行)

$(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 https://jsfiddle.net/vnfts73o/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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