vue引入安装并引入
import html2canvas from 'html2canvas' import jsPDF from 'jspdf'
截图时候忽略某个元素
ignoreElements: (element) => { if (element.id === 'back') {return true} }
截图整个页面 但是页面的右边容器带滚动条,需要将页面划分成几个部分,生成单独的canvas,然后新建一个空的canvas 将几个canvas合并到一个canvas上,带滚动条的容器,html2canvas传入的dom应该是容器的内容区域。每个canvas在合并的时候需要计算定位的坐标。
var c = document.createElement('canvas'); var ctx = c.getContext('2d'); c.width = this.$refs.titleZj.offsetWidth + 40 c.height = this.$refs.titleZj.offsetHeight html2canvas(this.$refs.titleZj, { backgroundColor: null, this.$refs.titleZj.offsetWidth, height: this.$refs.titleZj.offsetHeight, allowTaint: false, useCORS: true// 保证跨域图片的显示 }).then((canvas) => { ctx.drawImage(canvas, 20, 20); }) html2canvas(this.$refs.zjLeft, { backgroundColor: null, this.$refs.zjLeft.offsetWidth, height: this.$refs.zjLeft.offsetHeight, allowTaint: false, useCORS: true, // 保证跨域图片的显示 ignoreElements: (element) => { if (element.id === 'back') {return true} } }).then((canvas) => { ctx.drawImage(canvas, 20, this.$refs.titleZj.offsetHeight) }) // 导出图片看下效果 const a = document.createElement('a') const dom = document.body.appendChild(c) dom.style.display = 'none' a.style.display = 'none' const blob = this.dataURLToBlob(dom.toDataURL('image/png')) a.setAttribute('href', URL.createObjectURL(blob)) a.setAttribute('download', 'xxxxxx.png') document.body.appendChild(a) a.click() URL.revokeObjectURL(blob) document.body.removeChild(a)
导出pdf
const contentWidth = c.width; const contentHeight = c.height; // 一页pdf显示html页面生成的canvas高度; const pageHeight = contentWidth / 592.28 * 841.89; // 未生成pdf的html页面高度 let leftHeight = contentHeight; // 页面偏移 let position = 0; // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 const imgWidth = 595.28; const imgHeight = 592.28 / contentWidth * contentHeight; // document.getElementsByClassName('back')[0].style.visibility = 'hidden' const pageData = c.toDataURL('image/png'); // document.getElementsByClassName('back')[0].style.visibility = 'visible' 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(); } } } const date = this.setFormatter(this.currentValue.create) pdf.save(this.currentData.name + date + '.pdf')
注意:ie下如果a标签的href下载图片,base64格式如果太长是不可以的 需要转化成blob,然而ie9下base64转化成blob是不成功的