前端截图并导出pdf
实践
使用domtoimage和domToPdf
说明:
1 需要将页面的一个流程图导出
2 要求导出成pdf,且pdf上有标题等内容
做法:
因为导出的pdf中包含不存在页面上的内容
需要先将流程图截图成图片,再生成dom节点,之后导出成pdf
代码实现:
import domtoimage from 'dom-to-image';
import domToPdf from 'dom-to-pdf';exportToPngDirect() {if(this.exportLoading) returnthis.exportLoading = truethis.$message && this.$message.loading('导出中...')const container = document.querySelector('.life-main');if (!container) return;domtoimage.toPng(container, {bgcolor: '#F5F5F8',width: container.offsetWidth,height: container.offsetHeight,style: { 'background-color': '#F5F5F8' }}).then((dataUrl) => {this.base64Url = dataUrl;this.$nextTick(()=>{this.exportToPdf()})}).catch((error) => {this.$message.error('截图失败,请重试');this.exportLoading = false});},exportToPdf() {const title = '截图demo'// 1. 创建临时 DOMconst tempDiv = document.createElement('div');// 2. 填充内容tempDiv.innerHTML = `<h1 style="font-size:28px;text-align:center;margin:40px 0 20px 0;">流程引导图</h1><h2 style="font-size:18px;margin:0 0 20px 40px;">${title}</h2><img src="${this.base64Url}" style="max-width:100%;display:block;margin:0 auto;" />`;// 4. 导出 PDFdomToPdf(tempDiv, {filename: '流程图.pdf',pdf: { format: 'a4', orientation: 'portrait', unit: 'px' },image: { type: 'jpeg', quality: 0.98, backgroundColor: '#fff' }}, () => {this.exportLoading = falsethis.$message && this.$message.destroy()this.$message && this.$message.success('PDF导出成功!');});},
截图插件记录:
1 @zumer/snapdom
snapDOM – 以卓越的准确性和速度捕获 HTML 到图像
2 html2canvas
3 dom-to-image
对于更复杂的dom,dom-to-image比html2canvas更适合
snapDom 一个最新的截图插件,还没尝试,听说效率更高,更好用