求用html2canvas 分页生成图片到jspdf,完整代码。
时间: 2023-08-22 13:32:17 浏览: 112
好的,这是一个简单的示例代码,用于将HTML页面分页生成图片,并将所有图片合并为一个PDF文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>HTML2Canvas and jsPDF Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"></script>
</head>
<body>
<div id="content">
<h1>Page 1</h1>
<p>This is the content of page 1.</p>
</div>
<div id="content">
<h1>Page 2</h1>
<p>This is the content of page 2.</p>
</div>
<div id="content">
<h1>Page 3</h1>
<p>This is the content of page 3.</p>
</div>
<script>
$(document).ready(function() {
var totalPDFPages = 0;
var pdf = new jsPDF('p', 'pt', 'a4');
// Loop through all the HTML elements with id 'content'
$('div#content').each(function(index) {
var canvas = document.createElement('canvas');
var divHeight = $(this).height();
var divWidth = $(this).width();
var ratio = divHeight / divWidth;
var imgWidth = pdf.internal.pageSize.getWidth() - 20;
var imgHeight = imgWidth * ratio;
canvas.height = imgHeight;
canvas.width = imgWidth;
var contentDataURL = canvas.toDataURL('image/png');
html2canvas(this, {
scale: 1,
canvas: canvas
}).then(function(canvas) {
var imgData = canvas.toDataURL("image/png", 1.0);
pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
totalPDFPages++;
if (totalPDFPages === $('div#content').length) {
pdf.save('myPDF.pdf');
} else {
pdf.addPage();
}
});
});
});
</script>
</body>
</html>
```
这段代码使用了jQuery、html2canvas和jsPDF库,使用时需要先引入这些库。代码中,我们使用了html2canvas将HTML元素转换为canvas,并将canvas转换为base64格式的图片。然后,我们使用jsPDF将这些图片添加到PDF文件中,并将所有页面合并为一个PDF文件。注意,我们使用了一个计数器来跟踪生成的页面数,以便在所有页面都生成后才保存PDF文件。
阅读全文