js将html转换为pdf
所需引入文件
html2canvas和jsPdf.debug.js和jquery.min.js
贴代码:
点击下载 ,所需转换pdf的节点
我所遇到的问题是没有左右边距,。所以我将imgwidth调整了下大小。addImage左边距定义大小
一下为代码:
var downPdf = document.getElementById("renderPdf");
var s = document.getElementById("22");
downPdf.onclick = function() {
html2canvas(s, {
scale: 2,
useCORS: true,
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/png",1.0);
var imgWidth = 555.28; //297
var pageHeight = 592.28; //297
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
// var doc = new jsPDF('l', 'mm',[1350, 1350]);
var doc = new jsPDF('', 'pt', 'a4');
var position = 0; //0//上边距
margins = {
top: 20,
bottom: 10,
left: 45,
width: 522
};
doc.internal.scaleFactor = 1.33;
if (heightLeft < pageHeight) {
doc.addImage(imgData, 'JPEG', 20, position, imgWidth, imgHeight );
} else {
while(heightLeft > 0) {
pdf.addImage(imgData, 'JPEG', 20, position, imgWidth, imgHeight)//20为左边距
heightLeft -= pageHeight;
position -= 841.89;
//避免添加空白页
if(heightLeft > 0) {
pdf.addPage();
}
}
}
background: "#fff",
doc.save("2.pdf");
}
});
}