vue3 ts 导出PDF jsPDF-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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>

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue