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
相关推荐
FindYou.2 天前
基于mdEditor实现数据的存储和回显(导出pdf&表情包&目录)
javascript·vue
PD我是你的真爱粉3 天前
Vue3核心语法回顾与Composition深入
前端框架·vue
code袁4 天前
基于Springboot+Vue的家教小程序的设计与实现
vue.js·spring boot·小程序·vue·家教小程序
是梦终空4 天前
计算机毕业设计266—基于Springboot+Vue3的共享单车管理系统(源代码+数据库)
数据库·spring boot·vue·课程设计·计算机毕业设计·源代码·共享单车系统
是梦终空5 天前
计算机毕业设计267—基于Springboot+vue3+小程序的医院挂号系统(源代码+数据库)
spring boot·小程序·vue·毕业设计·课程设计·医院挂号系统·源代码
云游云记5 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue
沐墨染5 天前
黑词分析与可疑对话挖掘组件的设计与实现
前端·elementui·数据挖掘·数据分析·vue·visual studio code
集成显卡6 天前
前端视频播放方案选型:主流 Web 播放器对比 + Vue3 实战
前端·vue·音视频
克里斯蒂亚诺·罗纳尔达6 天前
vue页面加载时间过长优化
vue
草根大哥6 天前
AI编程实践-homex物业管理平台(Go + Vue3 + MySQL 多租户落地)
mysql·golang·vue·ai编程·gin·物业管理系统·多租户