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>
相关推荐
未来之窗软件服务34 分钟前
资源管理器必要性———仙盟创梦IDE
前端·javascript·ide·仙盟创梦ide
西哥写代码2 小时前
基于cornerstone3D的dicom影像浏览器 第十八章 自定义序列自动播放条
前端·javascript·vue
清风细雨_林木木2 小时前
Vue 中生成源码映射文件,配置 map
前端·javascript·vue.js
雪芽蓝域zzs3 小时前
JavaScript splice() 方法
开发语言·javascript·ecmascript
森叶3 小时前
Electron 主进程中使用Worker来创建不同间隔的定时器实现过程
前端·javascript·electron
霸王蟹4 小时前
React 19 中的useRef得到了进一步加强。
前端·javascript·笔记·学习·react.js·ts
霸王蟹4 小时前
React 19版本refs也支持清理函数了。
前端·javascript·笔记·react.js·前端框架·ts
繁依Fanyi4 小时前
ColorAid —— 一个面向设计师的色盲模拟工具开发记
开发语言·前端·vue.js·编辑器·codebuddy首席试玩官
codelxy4 小时前
vue引用cesium,解决“Not allowed to load local resource”报错
javascript·vue.js
程序猿阿伟5 小时前
《社交应用动态表情:RN与Flutter实战解码》
javascript·flutter·react native