vue实现pdf下载——html2canvas

html2canvas 官方文档https://html2canvas.hertzen.com/getting-started

html2canvas 的原理是通过遍历DOM树,将每一个HTML元素转化为Canvas对象,并叠加到一起形成一张完整的图片或者PDF文件

  1. 安装插件

npm install html2canvas jspdf --save

2.使用(页面已经写好)

2.1 在页面引入html2canvas

  1. import html2Canvas from 'html2canvas'

  2. import JsPDF from 'jspdf'

2.2 创建下载pdf页面的方法

javascript 复制代码
methods:{
        downloadPdf () {
            var title = "证书"
            html2Canvas(document.querySelector('#pdfDom'), {
                allowTaint: true
            }).then(function (canvas) {
                let contentWidth = canvas.width
                let contentHeight = canvas.height
                let pageHeight = contentWidth / 592.28 * 841.89
                let leftHeight = contentHeight
                let position = 0
                let imgWidth = 595.28
                let imgHeight = 592.28 / contentWidth * contentHeight
                let pageData = canvas.toDataURL('image/jpeg', 1.0)
                let PDF = new JsPDF('', 'pt', 'a4')
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= 841.89
                        if (leftHeight > 0) {
                        PDF.addPage()
                        }
                    }
                }
                PDF.save(title + '.pdf')
            })
        }
    }

2.3 页面调用下载方法

最终实现效果

原要下载的页面

  1. 下载的pdf
相关推荐
寰宇软件2 天前
PHP场馆预定系统小程序
小程序·uni-app·vue·php
躲在没风的地方3 天前
vue框架技术相关概述以及前端框架整合
node.js·vue
MickeyCV4 天前
万字长文总结前端开发知识---JavaScript&Vue3&Axios
开发语言·前端·javascript·vue·html·axios
雪球不会消失了4 天前
Vue5---
vue
心.c6 天前
Vue2下篇
开发语言·前端·javascript·vue
Sao_E6 天前
JWT实现单点登录
vue·状态模式·springboot
ThomasChan1238 天前
Typesrcipt泛型约束详细解读
前端·javascript·vue.js·react.js·typescript·vue·jquery
专注成就自我8 天前
解决npm install总是卡在sill idealTree buildDeps不动问题
前端·npm·node.js·vue
ThomasChan1239 天前
Typescript 多个泛型参数详细解读
前端·javascript·vue.js·typescript·vue·reactjs·js
寰宇软件10 天前
PHP防伪溯源一体化管理系统小程序
小程序·uni-app·vue·php