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>
相关推荐
阿奇__1 天前
element二次封装组件套餐 搜索组件 表格组件 弹窗组件
javascript·vue.js·elementui
The_era_achievs_hero1 天前
Echarts
前端·javascript·echarts
yesyesido1 天前
PDF全能管家:3合1智能处理,一键解锁高效文档管理新体验
科技·考研·安全·pdf·生活·交互·改行学it
亮子AI1 天前
【JavaScript】修改数组的正确方法
开发语言·javascript·ecmascript
chenhdowue1 天前
vxe-table 数据校验的2种提示方式
vue.js·vxe-table·vxe-ui
可触的未来,发芽的智生1 天前
微论-自成长系统引发的NLP新生
javascript·人工智能·python·程序人生·自然语言处理
八哥程序员1 天前
你真的理解了 javascript 中的原型及原型链?
前端·javascript
7ayl1 天前
Vue3 - runtime-core的渲染器初始化流程
前端·vue.js
隔壁的大叔1 天前
正则解决Markdown流式输出不完整图片、表格、数学公式
前端·javascript
San301 天前
深入 JavaScript 原型与面向对象:从对象字面量到类语法糖
javascript·面试·ecmascript 6