JSPDF – addHTML()多个canvas页面

我注意到已经有一个版本“addHTML()现在可以将canvas分成多个页面”,可以通过以下链接找到: https : //github.com/MrRio/jsPDF/releases/tag/v1.0.138 。

我可以知道它是如何工作的吗? 在我的情况下,我只是在点击“另存为pdf”按钮时尝试了它,它只渲染单个页面而不是多个页面(有时没有工作,我假设因为内容太长而无法生成为pdf) 。

如果这个案例有一些例子,我将不胜感激。 谢谢!

附上我的代码如下:

var pdf = new jsPDF('p', 'pt', 'a4'); pdf.addHTML($(".pdf-wrapper"), function () { var string = pdf.output('datauristring'); pdf.save("test.pdf"); }); 

通过提供“pagesplit”选项将canvas拆分为多个页面:

 var pdf = new jsPDF('p', 'pt', 'a4'); var options = { pagesplit: true }; pdf.addHTML($(".pdf-wrapper"), options, function() { pdf.save("test.pdf"); }); 

以上都没有帮助我所以我会把这个放在这里,任何到达此页面的人都希望使用addHTML()创建单个pdf拆分为多个页面,每个页面上都有不同的html元素。 我使用递归,所以我不确定这种方法的性能影响。 我可以从4个div元素创建一个4页的pdf。

 var pdf = new jsPDF('landscape'); var pdfName = 'test.pdf'; var options = {}; var $divs = $('.myDivClass') //jQuery object of all the myDivClass divs var numRecursionsNeeded = $divs.length -1; //the number of times we need to call addHtml (once per div) var currentRecursion=0; //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively. function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){ //Once we have done all the divs save the pdf if(currentRecursion==totalRecursions){ pdf.save(pdfName); }else{ currentRecursion++; pdf.addPage(); //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element //addHtml requires an html element. Not a string like fromHtml. pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){ console.log(currentRecursion); recursiveAddHtmlAndSave(currentRecursion, totalRecursions) }); } } pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){ recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded); }); } 

如果网页上有svg图像,则pdf.addHtml不起作用。我在这里复制解决方案://假设你的图片已经在canvas中var imgData = canvas.toDataURL(’image / png’); / *这是我发现工作的数字(纸张宽度和高度)。 它仍会在页面之间创建一个小的重叠部分,但对我来说足够好。 如果你能从jsPDF找到官方号码,请使用它们。 * /

 var imgWidth = 210; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; enter code here 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'); 

使用pagesplit: true它总是拉伸pdf输出。 尝试使用旧版本的jsPDF和html2canvas。

分享我2天试用的结果以使用addHTML而不是fromHTML来实现多页PDF生成,因为它失去了CSS规则。

   

那么PDF应该没问题如下:

  

希望这会有所帮助。 谢谢!