vue3 ts 导出PDF jsPDF

jsPDF 是一个基于 HTML5 的客户端解决方案,用于生成各种用途的 PDF 文档。

1、安装:npm install jspdf

npm install --save html2canvas

2、引入:import jsPDF from "jspdf"

import html2canvas from 'html2canvas'

3、使用

javascript 复制代码
<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>
相关推荐
天珩7 天前
操作word 以及pdf 记录以及踩坑总结
pdf·word·pdf转换·导出pdf·导出word
前端.攻城狮2 个月前
前端实现将多个页面导出为pdf(分页)
pdf·vue·jspdf
Ying(英子)5 个月前
前端用a标签实现静态资源文件(excel/word/pdf)下载
前端·导出pdf·纯前端下载·前端导出excel·前端下载功能·前端用a标签实现下载
Mr_Bobcp7 个月前
通过html2canvas和jsPDF将网页内容导出成pdf
pdf·html·html2canvas·jspdf