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
相关推荐
狼性书生7 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件
宇宙的最后一粒尘埃17 小时前
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
vue
清幽竹客1 天前
vue-18(使用 Vuex 插件实现高级功能)
前端·vue.js·前端框架·vue
牧码岛1 天前
Web前端之隐藏元素方式的区别、Vue循环标签的时候在同一标签上隐藏元素的解决办法、hidden、display、visibility
前端·css·vue·html·web·web前端
MINO吖2 天前
基于 qiankun + vite + vue3 构建微前端应用实践
vue·vite·微前端·qiankun·single-spa
Luffe船长2 天前
elementUI点击浏览table所选行数据查看文档
javascript·elementui·vue
IT瘾君2 天前
JavaWeb:前端工程化-ElementPlus
前端·elementui·node.js·vue
sunbyte3 天前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Dad Jokes(冷笑话卡片)
前端·javascript·css·vue.js·vue
幽络源小助理4 天前
SpringBoot+Vue+微信小程序校园自助打印系统
java·spring boot·微信小程序·小程序·vue
霸王蟹5 天前
从前端工程化角度解析 Vite 打包策略:为何选择 Rollup 而非 esbuild。
前端·笔记·学习·react.js·vue·rollup·vite