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
相关推荐
IT教程资源C16 小时前
(N_115)基于springboot,vue教务管理系统
mysql·vue·前后端分离·springboot教务系统
沧澜sincerely16 小时前
WebSocket 实时聊天功能
网络·websocket·vue·springboot
苏打水com16 小时前
第二十篇:Day58-60 前端性能优化进阶——从“能用”到“好用”(对标职场“体验优化”需求)
前端·css·vue·html·js
Jeking21717 小时前
进阶流程图绘制工具 Unione Flow Editor-- 直击行业痛点:高扩展性解决方案解析
vue·流程图·workflow·unione flow·flow editor·unione cloud
旧梦星轨17 小时前
掌握 Vite 环境配置:从 .env 文件到运行模式的完整实践
前端·前端框架·node.js·vue·react
sg_knight18 小时前
模块热替换 (HMR):前端开发的“魔法”与提速秘籍
前端·javascript·vue·浏览器·web·模块化·hmr
李慕婉学姐1 天前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
苏打水com2 天前
第十五篇:Day43-45 前端性能优化进阶——从“可用”到“极致”(对标职场“高并发场景优化”需求)
前端·css·vue·html·js
半桶水专家2 天前
vue3事件处理详解
vue
IT教程资源C2 天前
(N_122)基于springboot,vue网上订餐系统
mysql·vue·前后端分离·网上订餐系统·springboot网上订餐