html2canvas+jsPDF实现横向打印iframe中的内容
需要用到的插件:html2canvas jsPDF.debug.js jquery
html2canvas github地址:https://github.com/niklasvh/html2canvas
jsPDF和html2canvas插件已上传到我的阿里云网盘(需要自取),地址:
https://www.aliyundrive.com/s/auACtPpkw4w
效果预览
html2暂时不支持IE内核浏览器
//判断浏览器内核是否是IE
if(!!window.ActiveXObject || "ActiveXObject" in window){
alert('截图打印暂不支持IE内核浏览器,请更换火狐或谷歌chrome内核浏览器,360等双核浏览器请切换至极速模式');
return;
}
//获取iframe
var shareContent = document.getElementById('form_iframe');
//滚动iframe到顶部,如果不在顶部会截不完整
shareContent.contentWindow.scrollTo(0,0);
//获取iframe的宽高
var width = shareContent.contentWindow.document.documentElement.scrollWidth;
var height = shareContent.contentWindow.document.documentElement.scrollHeight;
var canvas = document.createElement("canvas"); //创建一个canvas节点
//定义任意放大倍数 支持小数,表单内容过多,请尽量往小了调。目前测试,打印3页chrome下会出现崩溃
var scale = 1.5;
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale ; //定义canvas高度 *缩放
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
var content = canvas.getContext("2d");
content.scale(scale,scale);
//配置canvas参数
var newOptions = {
scale:scale,
canvas : canvas,
background:"#ffffff",//设置背景色,避免打印iframe出现黑底
width: width,
height: height,
};
接着开始执行html2canvas截图以及生成pdf
//获取iframe Body
var frameBody = $('#form_iframe').contents().find('body');
html2canvas(frameBody, newOptions).then(function (canvas) {
//获取canvas画布的宽高
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth /841.89 * 592.28;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 841.89;
var imgHeight = 841.89/contentWidth * contentHeight;
var pageData = canvas.toDataURL();
var pdf = new jsPDF('l', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
}else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 592.28;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save("content.pdf");
});