<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>
var exportUtil = (function () {
/*思路:
1.将DOM转换为canvas
2.获取canvas的宽度、高度(稍微大一点,预览)
3.pdf的宽高设置为canvas的宽高(不适用A4纸大小)
4.将canvas转为图片
5.实例化jspdf,将内容图片放在pdf中
*/
//纸张
var pagers = {
"a4": [592.28, 841.89]
};
//创建临时DOM
function createTemDom(dom) {
let container = document.createElement("div");
container.style.position = "absolute";
container.style.overflow = "hidden";
container.style.opacity = 0;
let tempDom = dom.cloneNode(true);
tempDom.style.width = dom.scrollWidth + 'px';
tempDom.style.height = dom.scrollHeight + 'px';
container.appendChild(tempDom);
document.querySelector("body").appendChild(container);
return tempDom;
}
//保存为pdf
function saveAsPdf(dom, filename, pager) {
var getFirstChild = dom.children[0];
var secondchild = getFirstChild.children[1];
var thirdchild = secondchild.children[6];
thirdchild.style.display = "none";
var scale = 2;
let tempDom = createTemDom(dom);
//tempDom.style.background = "#FFFFFF";
html2canvas(tempDom, {
allowTaint: true,
scale: scale,
background: '#fff',
useCORS: true
}).then(function (canvas) {
//纸张大小
const p = (pager || 'a4').toLowerCase();
const pager_width = pagers[p][0];
const pager_height = pagers[p][1];
//画布与pdf页面尺寸计算
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = contentWidth / pager_width * pager_height;
let leftHeight = contentHeight;
let position = 30;
let imgWidth = pager_width;
let imgHeight = pager_width / contentWidth * contentHeight;
//canvas转图片
const imageData = canvas.toDataURL("image/jpeg");
tempDom.remove();
//创建jsPDF最后参数使用压缩,否则生成的pdf尺寸很大
const pdf = new jsPDF('', 'pt', 'a4', false);
if (leftHeight < pageHeight) {
//单页
pdf.addImage(imageData, 'JPEG', 0, 0, imgWidth, imgHeight, '', 'FAST');
} else {
//多页输出,计算偏移量
while (leftHeight > 0) {
pdf.addImage(imageData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST');
leftHeight -= pageHeight;
position -= pager_height;
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(filename)
});
};
return {
saveAsPdf: saveAsPdf
};
})();
//调用
var dom = document.querySelector(".formContentBox");
exportUtil.saveAsPdf(dom, "test.pdf", 'a4');