安装依赖:
首先,你需要安装 jspdf 和 html2canvas 这两个库。
bash
npm install jspdf html2canvas
创建Vue组件:
创建一个Vue组件,用于显示表格并提供导出PDF的功能。
bash
<template>
<div>
<div id="table-container">
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
</tr>
<!-- Add more rows as needed -->
</tbody>
</table>
</div>
<button @click="exportToPDF">Export to PDF</button>
</div>
</template>
<script>
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
export default {
name: 'TableToPDF',
methods: {
async exportToPDF() {
const tableContainer = document.getElementById('table-container');
const canvas = await html2canvas(tableContainer);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 190; // Adjust width according to your table width
const imgHeight = (canvas.height * imgWidth) / canvas.width;
pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
pdf.save('table.pdf');
},
},
};
</script>
<style scoped>
#table-container {
width: 100%;
max-width: 800px;
margin: 0 auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 8px;
text-align: left;
}
</style>