vue3 实现将html内容导出为图片、pdf和word
话不多说直接开始
本文使用到的开源插件库地址 wang1xiang
1.1 下载依赖
npm install html2canvas jspdf html-docx-js-typescript file-saver --save
2.1 下载工具
npm install html2image-pdf-word --save
3.1 页面使用
<template><div><div @click="htmlToPdfFn(1)">导出为图片</div><div @click="htmlToPdfFn(2)">导出为pdf</div><div @click="htmlToPdfFn(3)">导出为Word</div><div id="report" style="padding: 40px;"><el-table :data="tableData" style="width: 100%"><el-table-column type="selection" width="55" /><el-table-column label="Date" width="120"><template #default="scope">{{ scope.row.date }}</template></el-table-column><el-table-column property="name" label="Name" width="120" /><el-table-column property="address" label="use show-overflow-tooltip" width="240"show-overflow-tooltip /><el-table-column property="address" label="address" /></el-table><div>测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字</div><div>测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字</div><div>测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字,测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字</div></div></div>
</template><script setup lang="ts">
import { exportAsPdf, exportAsWord, exportAsImage } from 'html2image-pdf-word';
interface User {date: stringname: stringaddress: string
}
const tableData: User[] = [{date: '2016-05-04',name: 'Aleyna Kutzner',address: 'Lohrbergstr. 86c, Süd Lilli, Saarland',},{date: '2016-05-03',name: 'Helen Jacobi',address: '760 A Street, South Frankfield, Illinois',},{date: '2016-05-02',name: 'Brandon Deckert',address: 'Arnold-Ohletz-Str. 41a, Alt Malinascheid, Thüringen',},{date: '2016-05-01',name: 'Margie Smith',address: '23618 Windsor Drive, West Ricardoview, Idaho',},
]let htmlToPdfFn = async (type: number) => {const dom: any = document.querySelector('#report');const filename = 'test';switch (type) {case 1:await exportAsImage(dom, filename, '水印,水印水印');break;case 2:await exportAsPdf(dom, filename);break;case 3:await exportAsWord(dom, filename);break;}
}
</script>
<style scoped lang="scss"></style>