1.安装依赖
npm install html2canvas jspdf
2、引用
<template>
<div>
<button @click="exportPDF">导出为PDF</button>
<el-table border stripe size="small" highlight-current-row :style="{height:contentHeight}" :data="tableData" style="width: 100%" ref="multipleTableRef" @click="visibleZiChan = false" id="my-table">
</el-table>
</div>
</template>
<script lang="ts" setup>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const exportPDF = async () => {
const table = document.getElementById('my-table');
if(table){
const canvas = await html2canvas(table, { scale: 2 });
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('账户余额.pdf');
const newWindow = window.open();
if (newWindow) {
newWindow.document.write('<iframe src="' + pdf.output('bloburl') + '" width="100%" height="100%"></iframe>');
}
}
}
</script>