











在ElementUI中导出PDF通常涉及将页面上的DOM元素转换为PDF格式的文件。这一过程可以通过结合使用 html2canvas 和 jsPDF 这两个JavaScript库来实现。
在项目中安装html2canvas和jsPDF这两个库。可以通过npm进行安装:
npm install html2canvas jspdf
创建一个JavaScript文件(例如 htmlToPdf.js),并在其中定义导出PDF的函数。以下是一个示例函数:
import html2canvas from 'html2canvas'; import jsPDF from 'jspdf'; export function getPdf(elementId, pdfName) { const element = document.getElementById(elementId); html2canvas(element, { useCORS: true, // 允许跨域请求外部链接图片 allowTaint: true // 允许canvas污染 }).then(canvas => { const contentWidth = canvas.width; const contentHeight = canvas.height; const pageHeight = contentWidth / 592.28 * 841.89; let leftHeight = contentHeight; let position = 0; const imgWidth = 595.28; const imgHeight = (contentHeight * imgWidth) / contentWidth; const pageData = canvas.toDataURL('image/jpeg', 1.0); const pdf = new jsPDF('', 'pt', 'a4'); 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(); } } } pdf.save(pdfName + '.pdf'); }).catch(error => { console.error('Error during PDF generation:', error); }); }
在需要导出PDF的Vue组件中引入并使用这个函数。
例如:
<template> <div> <!-- 要导出的内容 --> <div id="exportContent"> <!-- 这里放置要导出的HTML内容 --> </div> <!-- 导出按钮 --> <el-button type="primary" @click="exportPdf">导出PDF</el-button> </div> </template> <script> import { getPdf } from './htmlToPdf'; // 引入导出的函数 export default { methods: { exportPdf() { getPdf('exportContent', '导出的文件名'); // 调用导出函数,并传入要导出的DOM元素的ID和PDF文件名 } } } </script>
html2canvas的配置中设置useCORS: true。此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。