async generatePDF() {const element = this.$refs.contentToPrint; // 你想要转换成PDF的DOM元素// 使用html2canvas将DOM元素转换成canvasconst canvas = await html2canvas(element);const imgData = canvas.toDataURL('image/png');// 创建PDF并添加图片const pdf = new jsPDF({orientation: 'portrait',unit: 'px',format: 'a4',});const imgProps = pdf.getImageProperties(imgData);const pdfWidth = pdf.internal.pageSize.getWidth();const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);pdf.save('download.pdf'); // 保存PDF},// generatePDF() { // const doc = new jsPDF() // doc.text("Hello world!", 10, 10) // doc.save("a4.pdf") // },
<div><el-button type="primary" @click="generatePDF">生成PDF</el-button> </div><div style="padding:20px 10px" ref="contentToPrint"></div>
解决图片无法显示问题
async generatePDF() {const element = document.getElementById('content'); // 你想要导出为PDF的DOM元素const opts = {scale: 4, // 缩放比例,提高生成图片清晰度useCORS: true, // 允许加载跨域的图片// allowTaint: false, // 允许图片跨域,和 useCORS 二者不可共同使用tainttest: true, // 检测每张图片都已经加载完成logging: true // 日志开关,发布的时候记得改成 false}const canvas = await html2canvas(element,opts);const imgData = canvas.toDataURL('image/png');const pdf = new jsPDF('p', 'mm', 'a4');const imgProps= pdf.getImageProperties(imgData);const pdfWidth = pdf.internal.pageSize.getWidth();const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);pdf.save('download.pdf');},