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>
相关推荐
不想有bug的小菜鸟5 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
quitv11 分钟前
react脚手架配置别名
前端·javascript·react.js
化作繁星22 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一只小姜丝3321 小时前
解决各大浏览器中http地址无权限调用麦克风摄像头问题
网络·vue.js·网络协议·http
Gazer_S2 小时前
【现代前端框架中本地图片资源的处理方案】
前端·javascript·chrome·缓存·前端框架
林的快手4 小时前
CSS默认样式
前端·css·vue.js·chrome·css3
贺今宵4 小时前
通过$attrs传递的未指定名称的modelValue值在子组件中修改
前端·javascript
lifire_H8 小时前
Canvas在视频应用中的技术解析
前端·javascript·音视频
林涧泣8 小时前
【Uniapp-Vue3】开发userStore用户所需的相关操作
前端·vue.js·uni-app
皓月当空hy10 小时前
vue3中测试:单元测试、组件测试、端到端测试
vue.js