vue将table转换为pdf导出

安装依赖:

首先,你需要安装 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>
相关推荐
一枚前端小能手2 分钟前
「周更第6期」实用JS库推荐:InversifyJS
前端·javascript
叉歪2 分钟前
纯前端函数,一个拖拽移动、调整大小、旋转、缩放的工具库
javascript
Hilaku3 分钟前
"事件委托"这个老古董,在现代React/Vue里还有用武之地吗?
前端·javascript·vue.js
向葭奔赴♡36 分钟前
前端框架学习指南:提升开发效率
前端·javascript·vue.js
小高00740 分钟前
🔥🔥🔥Vue 3.5 核弹级小补丁:useTemplateRef 让 ref 一夜失业?
前端·javascript·vue.js
一个不爱写代码的瘦子42 分钟前
Map、weakMap和Set、weakSet
前端·javascript
itslife1 小时前
vite 源码 -
前端·javascript
Nayana1 小时前
从项目架构开始了解Element-Plus组件库
javascript·前端框架
Mintopia1 小时前
动态数据驱动的 AIGC 模型:Web 端实时更新训练的技术可行性
前端·javascript·aigc
中微子1 小时前
Vue 2 与 Vue 3 组件写法对比
前端·javascript·vue.js