jsPDF 是一个基于 HTML5 的客户端解决方案,用于生成各种用途的 PDF 文档。
1、安装:npm install jspdf
npm install --save html2canvas
2、引入:import jsPDF from "jspdf"
import html2canvas from 'html2canvas'
3、使用
<template><div><a-button @click="handelChangeTime">pdf </a-button></div><div ref="chartRef"><h2>这里面添加需要导出的内容</h2><h3>支持表格、文字、图片、</h3><h3>原理就是将html生成为canvas图片,然后使用jsPDF将图片转为pdf</h3></div>
</template><script lang="ts" setup>
import { ref } from 'vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'// 获取需要转换为PDF的元素 ref
const chartRef = ref()
const handelChangeTime = () => {// 将元素转换为canvas对象html2canvas(chartRef.value).then((canvas) => {// 将canvas对象转换为图像const imgData = canvas.toDataURL('image/png')const pdf = new jsPDF()const imgProps = pdf.getImageProperties(imgData)const pdfWidth = pdf.internal.pageSize.getWidth()const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width// 将图像添加到PDF文件中pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight)// 保存PDF文件pdf.save('exported.pdf')})
}
</script><style lang="less" scoped></style>