很长一段时间以来,我一直试图用jsPDF创建一个多页PDF。
我有一个包含多个DIV的HTML文档
<div id="pdfContainer">
<div id="page1">Content page 1</div>
<div id="page2">Content page 2</div>
<div id="page3">Content page 3</div>
<div id="page4">Content page 4</div>
</div>
我用html2canvas尝试过,但更喜欢html2pdf (我有html2pdf.js)。
var doc = new jsPDF();
var elementHandler = {
'#page1': function (element, renderer) {
return true;
},
'#page2': function (element, renderer) {
return true;
},
'#page3': function (element, renderer) {
return true;
},
'#page4': function (element, renderer) {
return true;
}
};
var source = window.document.getElementById("pdfcontainer");
doc.fromHTML($('#pdfcontainer').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.output('dataurlnewwindow', {});
}
上面的代码是我的最后一次尝试,但会产生一个空PDF。
我也用过
var html = $('#page1').html();
html2pdf(html, pdf, function(pdf) {
pdf.output('dataurlnewwindow');
});
哪个有效,但仅适用于第1页
有没有简单的方法让这项工作?或者我必须逐页制作PDF页面
答案 0 :(得分:3)
使用html2pdf插件的简单示例:
<script>
var source = window.document.getElementById("report");
var pdf = new jsPDF('p', 'pt', 'a4');
var canvas = pdf.canvas;
canvas.height = 72 * 11;
canvas.width = 72 * 8.5;
//page break
pdf.context2d.pageWrapYEnabled = true;
html2pdf(source, pdf, function (pdf) {
var iframe = document.createElement('iframe');
iframe.setAttribute('style', 'position:fixed;right:0; top:0; bottom:0; height:100%; width:100%');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
}
);
</script>
答案 1 :(得分:1)
我们可以创建多个页面的PDF,但是用HTML分隔HTML格式的页面分区
然后我们可以将 jsPDF 和 html2canvas 结合起来,如下所示
var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".page1")[0], {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));
}
});
html2canvas($(".page2")[0], {
allowTaint: true,
onrendered: function(canvas) {
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var htmlH = $(".page2").height() + 100;
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addPage(580, htmlH);
pdf.addImage(imgData, 'PNG', 20, 20, (width - 40), (height));
}
});
html2canvas($(".page3")[0], {
allowTaint: true,
onrendered: function(canvas) {
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var htmlH = $(".page2").height() + 100;
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addPage(580, htmlH);
pdf.addImage(imgData, 'PNG', 20, 20, (width - 40), (height));
}
});
setTimeout(function() {
//jsPDF code to save file
pdf.save('sample.pdf');
}, 0);
这里给出了完整的教程http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/