使用canvas导出图片或者pdf
HTML:
1 <el-button size="small" type="primary" :loading="printLoading" @click="print($el, title, 'pdf')" >下载</el-button>
JS:
此按钮是在el-dialog中,传入的$el可更加实际情况调整。
1 import html2canvas from 'html2canvas'; 2 import { saveAs } from 'file-saver'; 3 import { jsPDF } from 'jspdf'; 4 5 methods: { 6 /** 7 * 导出为图片 8 * @param {Object} targetDom 目标DOM元素 9 * @param {String} title 导出标题 10 * @param {String} type 导出类型(图片或pdf) 11 * 若导出的图片中背景颜色有问题,需要调整样式 12 */ 13 print(targetDom, title, type) { 14 this.printLoading = true; 15 // DOM更改后 16 setTimeout(() => { 17 // 打印的时候忽略右上角的关闭按钮和最下方的打印报告按钮class类名 18 const excludeClass = ['el-dialog__headerbtn', 'footer']; 19 html2canvas(targetDom.children[0], { 20 backgroundColor: '#fff', 21 useCORS: true, //支持图片跨域 22 ignoreElements(element) { 23 return ( 24 element.classList && 25 Array.from(element.classList).some((key) => 26 excludeClass.includes(key) 27 ) 28 ); 29 } 30 }) 31 .then((canvas) => { 32 // 方式一:生成图片(避免分页问题) 33 if (type === 'pdf') { 34 this.createPDF(canvas, title); 35 } else { 36 canvas.toBlob((blob) => { 37 saveAs(blob, `${title}.png`); 38 }); 39 } 40 }) 41 .finally(() => (this.printLoading = false)); 42 }, 500); 43 }, 44 createPDF(canvas, title) { 45 const contentWidth = canvas.width; 46 const contentHeight = canvas.height; 47 48 //一页pdf显示html页面生成的canvas高度; 49 const pageHeight = (contentWidth / 592.28) * 841.89; 50 //未生成pdf的html页面高度 51 let leftHeight = contentHeight; 52 //页面偏移 53 let position = 20; 54 //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 55 const imgWidth = 595.28; 56 const imgHeight = (592.28 / contentWidth) * contentHeight; 57 58 const pageData = canvas.toDataURL('image/jpeg', 1.0); 59 60 // pdf实例 61 const pdf = new jsPDF('', 'pt', 'a4'); 62 63 //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) 64 //当内容未超过pdf一页显示的范围,无需分页 65 if (leftHeight < pageHeight) { 66 pdf.addImage(pageData, 'JPEG', 20, 20, imgWidth - 40, imgHeight - 40); 67 } else { 68 while (leftHeight > 0) { 69 pdf.addImage( 70 pageData, 71 'JPEG', 72 20, 73 position, 74 imgWidth - 40, 75 imgHeight - 40 76 ); 77 leftHeight -= pageHeight; 78 position -= 841.89; 79 //避免添加空白页 80 if (leftHeight > 0) { 81 pdf.addPage(); 82 } 83 } 84 } 85 //输出保存命名为content的pdf 86 pdf.save(title + '.pdf'); 87 } 88 }
分类:
vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)