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>
相关推荐
掘金01几秒前
在 Vue 3 项目中使用 MQTT 获取数据
前端·javascript·vue.js
QuantumLeap丶几秒前
《uni-app跨平台开发完全指南》- 03 - Vue.js基础入门
前端·vue.js·uni-app
一 乐15 分钟前
个人理财系统|基于java+小程序+APP的个人理财系统设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·后端·小程序
wyzqhhhh24 分钟前
同时打开两个浏览器页面,关闭 A 页面的时候,要求 B 页面同时关闭,怎么实现?
前端·javascript·react.js
晴殇i25 分钟前
从 WebSocket 到 SSE:实时通信的轻量化演进
前端·javascript
网络点点滴26 分钟前
reactive创建对象类型的响应式数据
前端·javascript·vue.js
熊猫比分站1 小时前
[特殊字符] Java/Vue 实现体育比分直播系统,支持多端实时更新
java·开发语言·vue.js
多则惑少则明2 小时前
Vue开发系列——自定义组件开发
前端·javascript·vue.js
一叶难遮天2 小时前
开启RN之旅——前端基础
前端·javascript·promise·js基础·es6/ts·npm/nrm
BetterChinglish2 小时前
html5中canvas图形变换transform、setTransform原理(变换矩阵)
javascript·html5·canvas·变换矩阵