TIP
利用html2canvas.js和jspdf.js将网页转为pdf
- pdf模糊问题
canvas放大处理
- 内容缺失,或偏移
margin translate
和滚动条等有影响,要恢复到初始位置
js
function toPdf() {
window.scrollTo(0,0); // 避免内容缺失
document.querySelector('.print-btns').style = 'display: none';
var oContentBox = document.querySelector("#contentBox");
oContentBox.style = 'margin: 0'; // 避免内容缺失
var boxWidth = oContentBox.offsetWidth;
var boxHeight = oContentBox.offsetHeight;
var canvas = document.createElement("canvas");
var scale = 5; // 处理模糊问题
canvas.width = boxWidth*scale;
canvas.height = boxHeight*scale;
var ctx = canvas.getContext("2d");
ctx.scale(scale, scale);
new html2canvas( oContentBox,
{
canvas,
foreignObjectRendering: true, // 设置这个,发现我的图片不显示了,删除这个能显示了,但是内容显示又不全,将scale设为1解决问题
scale: window.devicePixelRatio * scale,
width: boxWidth,
height: boxHeight,
scrollX: 0,
scrollY: 0,
onrendered: function (canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89])
var imgWidth = 595.28;
var imgHeight = imgWidth/ contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', '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 -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
document.querySelector('.print-btns').style = '';
oContentBox.style = '';
},
//背景设为白色(默认为黑色)
background: "#fff"
})
}
TIP
关于超出一页内容被截断的问题,可以通过判断单元格距离文档顶部的距离,是否大于一页a4纸的高度,来添加一个额外的空白块。(是个思路,demo里没有)
js
//获取元素距离顶部和左侧的距离
function offset(element) {
var pos = { left: 0, top: 0 }
var parents = element.offsetParent
pos.left += element.offsetLeft
pos.top += element.offsetTop
while (parents && !/html|body/i.test(parents.tagName)) {
pos.left += parents.offsetLeft
pos.top += parents.offsetTop
parents = parents.offsetParent
}
return pos
}