1、引入html2canvas.js
2、html,用id为pdf包含要下载的区域
<div style="width:100%;height:auto" id="pdf">
<div>要下载的区域</div>
</div>
3、js,点击按钮触发Easyuisave()事件
$("#submit",parent.document).on("click",function(){//下载图片pdf
if($("#ff").form("validate")){
Easyuisave({
elem:$("#ff").serialize(),
});//调用子页面方法
top.layer.closeAll();//关闭弹窗
return false;
}else{
msg({
layer:layer,
title:"请完善表格内容!"
});
}
});
4、封装Easyuisave()事件
function Easyuisave(obj){//submit
$("#edit").click();
html2canvas(document.getElementById("box"), {
height:document.getElementById("pdf").offsetHeight+60,
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 10;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', ["612.28",imgHeight]);
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
//if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG',10, 0, imgWidth, imgHeight );
/* } else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
} */
pdf.save("电气运行报告"+".pdf");
}
})
}
注意:如果有滚动条,可能会下载不全,需要用锚点定位到页面顶部