exportPdf【导出PDF】
描述
通过传入 Dom 节点或 css 选择器,导出 pdf。
感谢 由黄金苏同学提供。👏👏👏
⚠️ 警告
使用该方法,是依赖 html2canvas (opens new window) 和 jspdf (opens new window) 这两个库。
在本 utils 工具库中默认没有安装,需要使用者在自己的项目中安装。
我们推荐版本 html2canvas@1.4.0 jspdf@2.3.0
# 1.依赖 html2canvas 和 jspdf 库安装
yarn add html2canvas@1.4.0 jspdf@2.3.0
1
npm i html2canvas@1.4.0 jspdf@2.3.0
1
// Make sure to add code blocks to your code group
# 2.示例
复制代码
# 3.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| target | 目标元素,可以是 Dom 节点 也可以是 css 选择器 | String HTMLHtmlElement | - | - |
| title | 导出的文件名,不要加扩展名 | String | - | - |
# 4.源码
源码,点开查看 👈
import html2canvas from 'html2canvas'
import Jspdf from 'jspdf'
import isString from '@/base/isString'
/**
* 导出页面为PDF格式,依赖【缺少 html2canvas库】:推荐版本1.4.0;依赖【缺少 jspdf库】:推荐版本2.3.0
* @param {String | HTMLHtmlElement} target 目标元素
* @param {String } title 导出的文件名
* @returns {Promise<void>}
*/
async function exportPdf(target, title) {
let _targetDom = target
if (isString(target)) {
_targetDom ||= document.querySelector(target)
}
if (!_targetDom) {
throw new Error('【error】:传入的target 非正常的选择器或dom元素')
}
html2canvas(_targetDom, {
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')
})
}
export default exportPdf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
上次更新: 2025/07/01, 14:52:29