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 天前
计算机源码273—基于SpringBoot+Vue3停车场管理系统带支沙箱支付(源代码+数据库)
数据库·spring boot·vue·mybatis·停车场管理系统·沙箱支付·毕设设计
_Twink1e2 天前
基于Vue的纯前端的库存销售系统
前端·vue.js·vue·web
灵魂学者2 天前
使用 Electron 打包项目构建 .EXE 桌面应用程序(简)
electron·node.js·vue·build·桌面应用程序
Zephyr_02 天前
SQL,MyBatis-Plus,maven,Spring与VUE3
sql·spring·vue·maven·mybatis
:mnong3 天前
附图报价系统设计分析5
electron·pdf·vue·cad·dwg·定额
桃花键神3 天前
【2026精品项目】基于SpringBoot3+Vue3的旧物置换系统(包含源码+项目文档+SQL脚本+部署教程)
数据库·spring boot·sql·vue
FlyWIHTSKY3 天前
**Vue 3 `<script setup>` 语法糖** 中的一行解构赋值,用来**从父组件透传下来的属性(attrs)
vue
CAE虚拟与现实3 天前
前后端调试常用工具大全
前端·后端·vue·react·angular
web行路人4 天前
前端对Commands(斜杠命令)一些常用
前端·javascript·vue.js·vue
布局呆星5 天前
Spring Boot+MyBatis-Plus+Vue3前后端协作Note
spring boot·typescript·vue·mybatis