前端处理导出PDF。Vue导出pdf

前言:该篇主要是解决一些简单的页面内容导出为PDF

1.安装依赖

使用到两个依赖,项目目录下运行这两个

javascript 复制代码
//页面转换成图片
npm install --save html2canvas 
//图片转换成pdf
npm install jspdf --save 

2.创建通用工具类exportPdf.js文件

可以保存在工具类目录下;

javascript 复制代码
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export function getPdf(title, id) {
  // 参数校验
  if (!title || !id) {
    console.error('Title and ID are required.')
    return
  }

  const element = document.querySelector(`#${id}`)
  if (!element) {
    console.error(`Element with ID "${id}" not found.`)
    return
  }

  html2Canvas(element, {
    allowTaint: true,
    useCORS: true,
    scale: 2
  }).then(function (canvas) {
    const contentWidth = canvas.width
    const contentHeight = canvas.height

    // A4纸尺寸 (单位: pt)
    const a4Width = 595.28
    const a4Height = 841.89

    // 设置外边距 (单位: pt)
    const marginLeft = 20
    const marginTop = 20
    const marginRight = 20
    const marginBottom = 20

    // 计算可用内容区域
    const availableWidth = a4Width - marginLeft - marginRight
    const availableHeight = a4Height - marginTop - marginBottom

    // 计算缩放比例,使内容宽度适配可用区域
    const scale = availableWidth / contentWidth

    // 按比例计算图像在页面上的尺寸
    const imgWidth = contentWidth * scale
    const imgHeight = contentHeight * scale

    // 计算每页可容纳的高度(考虑上下边距)
    const pageHeight = availableHeight
    let leftHeight = imgHeight
    let position = 0

    const pageData = canvas.toDataURL('image/jpeg', 0.95)
    const PDF = new JsPDF('', 'pt', 'a4')

    if (leftHeight < pageHeight) {
      // 内容高度小于页面可用高度,直接添加图片(带外边距)
      PDF.addImage(pageData, 'JPEG', marginLeft, marginTop, imgWidth, imgHeight)
    } else {
      // 内容高度大于页面可用高度,分页处理
      while (leftHeight > 0) {
        // 添加当前页面图像(带外边距)
        PDF.addImage(pageData, 'JPEG', marginLeft, marginTop + position, imgWidth, imgHeight)
        leftHeight -= pageHeight
        position -= a4Height

        // 如果还有剩余内容,添加新页面
        if (leftHeight > 0) {
          PDF.addPage()
        }
      }
    }

    PDF.save(title + '.pdf')
  }).catch(function (error) {
    console.error('PDF导出失败:', error)
  })
}

3.Demo例子

javascript 复制代码
<template>
    <div>
        <!-- 容器 -->
        <div id="pdfHtml" ref="printHtml">
            <h1>这是一个Demo。</h1>
        </div>
        <button @click="exportPDF">PDF导出</button>
    </div>
</template>
<script>
import { getPdf } from '@/utils/exportPdf';
export default {
    methods: {
        // 导出pdf
        exportPDF() {
            getPdf('关键因素', 'pdfHtml');
        }
    }
}
</script>
相关推荐
你的电影很有趣18 分钟前
lesson77:Vue组件开发指南:从基础使用到高级通信
javascript·vue.js·1024程序员节
Mr.Jessy38 分钟前
JavaScript学习第六天:函数
开发语言·前端·javascript·学习·html·1024程序员节
code_YuJun1 小时前
管理系统——应用初始化 Loading 动画
前端
oak隔壁找我1 小时前
JavaScript 模块化演进历程:问题与解决方案。
前端·javascript·架构
Elieal1 小时前
AJAX 知识
前端·ajax·okhttp
sulikey2 小时前
Qt 入门简洁笔记:从框架概念到开发环境搭建
开发语言·前端·c++·qt·前端框架·visual studio·qt框架
烛阴2 小时前
循环背后的魔法:Lua 迭代器深度解析
前端·lua
元拓数智2 小时前
现代前端状态管理深度剖析:从单一数据源到分布式状态
前端·1024程序员节
mapbar_front3 小时前
Electron 应用自动更新方案:electron-updater 完整指南
前端·javascript·electron
星空的资源小屋3 小时前
Antares SQL,一款跨平台开源 SQL 客户端
数据库·人工智能·pdf·开源·电脑·excel·1024程序员节