当前位置: 首页 > article >正文

前端导出页面PDF

import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { Loading } from 'element-ui'
let downloadLoadingInstance

// 导出页面为PDF格式---使用插件html2canvas和jspdf插件
export function exportPDF(fileName, node) {
  downloadLoadingInstance = Loading.service({ text: 'データをダウンロード中です。しばらくお待ちください', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  document.body.scrollTop = document.documentElement.scrollTop = 0
  var clientH = node.clientHeight
  node.style.height = node.scrollHeight + 'px'// 把要导出的元素高度设置为滚动高度

  html2canvas(node, {
    allowTaint: true,
    useCORS: true,
    backgroundColor: '#142D42', // 如果指定的div没有设置背景色会默认成黑色,这里是个坑
    y: 0,
    ignoreElements: element => {
      if (element.tagName === 'BUTTON' ||
       typeof element.className !== 'string' ||
        (typeof element.className === 'string' && element.className.includes('sidebar-container')) ||
        (typeof element.className === 'string' && element.className.includes('navbar')) ||
        (typeof element.className === 'string' && element.className.includes('tags-view-container')) ||
        (typeof element.className === 'string' && element.className.includes('operation-bar')) ||
        element.tagName === 'svg'
      ) {
        return true
      }
      return false
    }
  }).then((canvas) => {
    // 未生成pdf的html页面高度
    var leftHeight = canvas.height
    var a4Width = 576
    var a4Height = 772.89 // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
    // 一页pdf显示html页面生成的canvas高度;
    var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height)
    // pdf页面偏移
    var position = 0
    var pageData = canvas.toDataURL('image/jpeg', 1.0)
    var pdf = new jsPDF('p', 'pt', 'a4') // A4纸,纵向
    // pdf.addFont('simkai-normal.ttf', 'simkai', 'normal')
    // pdf.setFont('simkai')
    // pdf.setFontSize(20)
    var canvas1 = document.createElement('canvas')
    var height
    pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen')

    function createImpl(canvas) {
      if (leftHeight > 0) {
        var checkCount = 0
        if (leftHeight > a4HeightRef) {
          var i = position + a4HeightRef
          for (i = position + a4HeightRef; i >= position; i--) {
            var isWrite = true
            for (var j = 0; j < canvas.width; j++) {
              var c = canvas.
                getContext('2d').
                getImageData(j, i, 1, 1).data
              if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
                isWrite = false
                break
              }
            }
            if (isWrite) {
              checkCount++
              if (checkCount >= 10) {
                break
              }
            } else {
              checkCount = 0
            }
          }
          height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef)
          if (height <= 0) {
            height = a4HeightRef
          }
        } else {
          height = leftHeight
        }

        canvas1.width = canvas.width
        canvas1.height = height
        var ctx = canvas1.getContext('2d')
        ctx.drawImage(
          canvas,
          0,
          position,
          canvas.width,
          height,
          0,
          0,
          canvas.width,
          height
        )
        if (position !== 0) {
          pdf.addPage()
        }
        pdf.addImage(
          canvas1.toDataURL('image/jpeg', 1.0),
          'JPEG',
          10,
          40,
          a4Width,
          (a4Width / canvas1.width) * height
        )
        leftHeight -= height
        position += height
        if (leftHeight > 0) {
          setTimeout(createImpl, 500, canvas)
        } else {
          pdf.save(fileName + '.pdf')
          // 下载完成后改变浏览器界面可视区域高度
          node.style.height = clientH + 'px'
        }
      }
      node.style.height = 'initial'
      downloadLoadingInstance.close()
    }
    // 当内容未超过pdf一页显示的范围,无需分页
    if (leftHeight < a4HeightRef) {
      pdf.addImage(
        pageData,
        'JPEG',
        10,
        40,
        a4Width,
        (a4Width / canvas.width) * leftHeight
      )
      pdf.save(fileName + '.pdf')
      // 下载完成后改变浏览器界面可视区域高度
      node.style.height = clientH + 'px'
    } else {
      try {
        pdf.deletePage(0)
        setTimeout(createImpl, 500, canvas)
      } catch (err) {
        console.log('err', err)
      }
    }
    node.style.height = 'initial'
    downloadLoadingInstance.close()
  })
}

使用的时候直接引入

import { exportPDF } from './exportPDF'


    exportPdf() {
      if (this.drChange) {
        exportPDF(`[${this.wakuGroup.grpWkMei}]_[${this.nen}年${this.textSeason}]${this.$moment().format('YYYYMMDDHHmmss')}`, this.$refs.collapse.$el)
      } else {
        exportPDF(`[${this.wakuGroup.grpWkMei}]_[${this.nen}年${this.textSeason}]_${this.$moment().format('YYYYMMDDHHmmss')}`, this.$refs.collapse.$el)
      }
    },


http://www.kler.cn/news/327306.html

相关文章:

  • rust的nutyp验证和validator验证数据的方法
  • MySQL | group by 用法
  • 牛客周赛 Round 62
  • 828华为云征文|部署个人文档管理系统 Docspell
  • Kali Linux安全工具
  • 实战OpenCV之形态学操作
  • 网络带宽对于服务器的影响
  • 云原生之运维监控实践-使用Prometheus与Grafana实现对MySQL和Redis服务的监测
  • Drf认证组件
  • Feign 主要负责简化 HTTP API 的调用逻辑; Eureka 负责服务实例的注册和服务发现; Ribbon 则负责实现客户端的负载均衡。
  • UE4_Niagara基础实例—7、如何让粒子照亮周边环境
  • 制造企业各部门如何参与生产成本控制与管理?
  • Leetcode Hot 100 | 543.二叉树的直径 | 递归+优化
  • 【人人保-注册安全分析报告-无验证方式导致安全隐患】
  • 项目:微服务即时通讯系统客户端(基于C++QT)]四,中间界面搭建和逻辑准备
  • git使用“保姆级”教程3——添加暂存区及提交本地库
  • 苹果手机如何录屏?IOS 自带工具与嗨格式录屏大师 APP 详解
  • 只写CURD后台管理的Java后端要如何提升自己
  • RabbitMQ的应用问题
  • ansible学习之 Facts
  • Python知识点:如何使用EdgeX Foundry与Python进行边缘计算
  • 使用iTextPDF库时,设置文字为中文格式
  • 基于微信小程序的美食推荐系统
  • 鸿蒙NEXT入门到实战(基于最新api12稳定版)
  • DevExpress WinForms中文教程:Data Grid - 如何添加或删除行?
  • 基于springboot的评分评教管理系统
  • C#进阶-读写Excel常用框架及其使用方式
  • Edge SCDN:安全与速度并进的解决方案
  • C嘎嘎入门篇:类和对象(2)
  • JVM运行情况预估