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>
相关推荐
炫饭第一名13 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
Forever7_13 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码114 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial14 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
进击的尘埃14 小时前
Vue3 响应式原理:从 Proxy 到依赖收集,手撸一个迷你 reactivity
javascript
willow14 小时前
JavaScript数据类型整理1
javascript
LeeYaMaster15 小时前
20个例子掌握RxJS——第十一章实现 WebSocket 消息节流
javascript·angular.js
UIUV15 小时前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
SuperEugene15 小时前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
阿懂在掘金16 小时前
defineModel 是进步还是边界陷阱?双数据源组件的选择逻辑
vue.js·源码阅读