如何使用jsPDF和HTML2Canvas从网站获取多页pdf? [英] How do I get a multi-page pdf from a website using jsPDF and HTML2Canvas?

查看:280
本文介绍了如何使用jsPDF和HTML2Canvas从网站获取多页pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,该脚本使用HTML2Canvas捕获页面内div的屏幕截图,然后使用jsPDF将其转换为pdf.

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.

问题在于生成的pdf仅为一页,并且在某些情况下屏幕截图需要一页以上.例如,屏幕截图大于8.5x11.宽度很好,但是我需要它来创建多个页面以适合整个屏幕截图.

The problem is the pdf that is generated is only one page, and the screenshot requires more than one page in some instances. For example the screenshot is larger than 8.5x11. The width is fine, but I need it to create more than one page to fit the entire screenshot.

这是我的剧本:

var pdf = new jsPDF('portrait', 'pt', 'letter');
$('.export').click(function() {
      pdf.addHTML($('.profile-expand')[0], function () {
           pdf.save('bfc-schedule.pdf');
      });
 });

有什么想法可以修改它以允许多个页面吗?

Any ideas how I could modify that to allow for multiple pages?

推荐答案

pdf.addHtml不起作用. 我在这里根据已经在画布中的图片复制解决方案.

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.

这是我发现可以使用的数字(纸张宽度和高度).它仍然在页面之间创建了一些重叠的部分,但是对我来说足够好了.如果您可以从jsPDF中找到正式编号,请使用它们.

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

这篇关于如何使用jsPDF和HTML2Canvas从网站获取多页pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆