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>
相关推荐
烛阴33 分钟前
开发者神器:如何在浏览器控制台玩转第三方库,让调试效率翻倍!
前端·javascript
拉不动的猪1 小时前
JQ常规面试题
前端·javascript·面试
新中地GIS开发老师2 小时前
三维GIS开发cesium智慧地铁教程(5)Cesium相机控制
javascript·arcgis·智慧城市·大学生·gis开发·webgis·地理信息科学
Shimeng_19892 小时前
前端如何通过(手机)扫描二维码下载app
前端·javascript·vue.js·二维码·扫描二维码下载软件app
Mr...Gan2 小时前
TypeScript
开发语言·javascript·typescript
MZWeiei3 小时前
MVVM 模式,以及 Angular、React、Vue 和 jQuery 的区别与关系
vue.js·react.js·angular.js
前端 贾公子3 小时前
《Vuejs设计与实现》第 8 章(挂载与更新)
开发语言·前端·javascript
述雾学java3 小时前
Spring Boot + Vue 前后端分离项目解决跨域问题详解
vue.js·spring boot·后端
半碗水4 小时前
缝缝补补
前端·javascript
用户2519162427114 小时前
ES6之类的其他书写方式
javascript·ecmascript 6