# html导出pdf
# 封装
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
/**
* PDF导出工具类
* 使用说明:
* 1. 创建实例: let pdfExporter = new PdfExporter(element, options);
* 2. 导出PDF: pdfExporter.exportPdf(fileName, isDownload).then(pdf => {...});
*
* @class PdfExporter
* @param {HTMLElement} ele - 需要导出PDF的DOM元素
* @param {Object} options - 配置选项
* @param {string} [options.pdfFileName='document'] - 导出PDF的文件名
* @param {string} [options.splitClassName='itemClass'] - 避免分页截断的类名
* @param {string} [options.breakClassName='break_page'] - 分页符类名
* @param {number} [options.quality=1.0] - 图片质量 (0-1)
* @param {number} [options.margin=5] - 页面边距(像素)
*/
class PdfExporter {
constructor(ele, options = {}) {
if (!ele || !(ele instanceof HTMLElement)) {
throw new Error('必须提供有效的DOM元素');
}
// 配置选项
const {
pdfFileName = 'document',
splitClassName = 'itemClass',
breakClassName = 'break_page',
quality = 1.0,
margin = 5
} = options;
this.ele = ele;
this.pdfFileName = pdfFileName;
this.splitClassName = splitClassName;
this.breakClassName = breakClassName;
this.quality = quality;
this.margin = margin;
// A4尺寸(像素)
this.A4_WIDTH = 595;
this.A4_HEIGHT = 842;
// 内部状态
this.pageHeight = 0;
this.pageNum = 1;
}
/**
* 生成PDF
* @private
* @param {Function} resolve - Promise resolve函数
* @param {Function} reject - Promise reject函数
* @param {boolean} isDownload - 是否下载PDF
* @returns {Promise}
*/
async generatePDF(resolve, reject, isDownload) {
try {
const ele = this.ele;
const eleW = ele.offsetWidth;
const eleH = ele.scrollHeight;
const eleOffsetTop = ele.offsetTop;
const eleOffsetLeft = ele.offsetLeft;
// 计算滚动条宽度
const scrollBarWidth = this.calculateScrollbarWidth();
// 创建canvas并设置尺寸
const canvas = document.createElement('canvas');
canvas.width = eleW * 2;
canvas.height = eleH * 2;
const context = canvas.getContext('2d');
context.scale(2, 2);
context.translate(-eleOffsetLeft - scrollBarWidth, -eleOffsetTop);
// 使用html2canvas渲染元素
const renderedCanvas = await html2canvas(ele, {
useCORS: true,
scale: 2,
logging: false,
backgroundColor: '#ffffff'
});
const contentWidth = renderedCanvas.width;
const contentHeight = renderedCanvas.height;
// 计算页面高度和图片尺寸
this.pageHeight = (contentWidth / this.A4_WIDTH) * this.A4_HEIGHT;
const imgWidth = this.A4_WIDTH - (this.margin * 2);
const imgHeight = (this.A4_WIDTH / contentWidth) * contentHeight;
const pageData = renderedCanvas.toDataURL('image/jpeg', this.quality);
const pdf = new jsPDF('', 'pt', 'a4');
let leftHeight = contentHeight;
let position = 0;
// 添加图片到PDF
if (leftHeight < this.pageHeight) {
// 单页
pdf.addImage(pageData, 'JPEG', this.margin, 0, imgWidth, imgHeight);
} else {
// 多页
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', this.margin, position, imgWidth, imgHeight);
leftHeight -= this.pageHeight;
position -= this.A4_HEIGHT;
if (leftHeight > 0) {
pdf.addPage();
}
}
}
// 清理并返回结果
if (isDownload) {
pdf.save(`${this.pdfFileName}.pdf`);
this.cleanupEmptyDivs();
}
this.ele.style.height = '';
resolve(pdf);
} catch (error) {
console.error('生成PDF时出错:', error);
reject(error);
}
}
/**
* 导出PDF
* @param {string} [pdfFileName] - 可选的PDF文件名
* @param {boolean} [isDownload=true] - 是否下载PDF
* @returns {Promise} 返回包含PDF对象的Promise
*/
exportPdf(pdfFileName = null, isDownload = true) {
return new Promise((resolve, reject) => {
try {
// 更新文件名(如果提供)
if (pdfFileName) {
this.pdfFileName = pdfFileName;
}
// 重置状态
this.pageNum = 1;
this.ele.style.height = 'initial';
// 计算页面高度
const target = this.ele;
this.pageHeight = (target.scrollWidth / this.A4_WIDTH) * this.A4_HEIGHT;
// 处理分页
this.processPagination(this.ele);
// 生成PDF
this.generatePDF(resolve, reject, isDownload);
} catch (error) {
reject(error);
}
});
}
/**
* 处理分页逻辑
* @private
* @param {HTMLElement} dom - 要处理的DOM元素
*/
processPagination(dom) {
const childNodes = dom.childNodes;
childNodes.forEach((childDom) => {
// 处理需要避免截断的元素
if (this.hasClass(childDom, this.splitClassName)) {
this.handleSplitElement(childDom);
}
// 处理分页符
if (this.hasClass(childDom, this.breakClassName)) {
this.handleBreakElement(childDom);
}
// 递归处理子元素
if (childDom.childNodes && childDom.childNodes.length > 0) {
this.processPagination(childDom);
}
});
}
/**
* 处理需要避免截断的元素
* @private
* @param {HTMLElement} element - 需要处理的元素
*/
handleSplitElement(element) {
const eleBounding = this.ele.getBoundingClientRect();
const bound = element.getBoundingClientRect();
const currentPage = Math.ceil((bound.bottom - eleBounding.top) / this.pageHeight);
if (this.pageNum < currentPage) {
this.pageNum++;
const parent = element.parentNode;
const newNode = document.createElement('div');
newNode.className = 'pdf-empty-div';
newNode.style.background = 'white';
newNode.style.height = `${this.pageHeight * (this.pageNum - 1) - (bound.top - eleBounding.top) + 30}px`;
newNode.style.width = '100%';
parent.insertBefore(newNode, element);
}
}
/**
* 处理分页符元素
* @private
* @param {HTMLElement} element - 分页符元素
*/
handleBreakElement(element) {
this.pageNum++;
const eleBounding = this.ele.getBoundingClientRect();
const bound = element.getBoundingClientRect();
const offset2Ele = bound.top - eleBounding.top;
const alreadyHeight = offset2Ele % this.pageHeight;
const remainingHeight = this.pageHeight - alreadyHeight + 20;
element.style.height = `${remainingHeight}px`;
}
/**
* 检查元素是否包含指定类名
* @private
* @param {HTMLElement} element - DOM元素
* @param {string} cls - 类名
* @returns {boolean}
*/
hasClass(element, cls) {
if (!element || !element.className) return false;
return element.className.split(' ').includes(cls);
}
/**
* 计算滚动条宽度
* @private
* @returns {number} 滚动条宽度
*/
calculateScrollbarWidth() {
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.overflow = 'scroll';
document.body.appendChild(outer);
const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
/**
* 清理添加的空div
* @private
*/
cleanupEmptyDivs() {
const emptyDivs = document.querySelectorAll('.pdf-empty-div');
emptyDivs.forEach(div => div.remove());
}
}
export default PdfExporter;
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# 使用
// 获取要导出的DOM元素
const element = document.getElementById('content-to-export');
// 创建PdfExporter实例
const pdfExporter = new PdfExporter(element, {
pdfFileName: 'my-document',
splitClassName: 'avoid-split',
breakClassName: 'page-break',
quality: 0.8,
margin: 10
});
// 导出PDF并下载
pdfExporter.exportPdf('my-file-name', true);
// 或者获取PDF对象而不直接下载
pdfExporter.exportPdf('my-file-name', false).then(pdf => {
// 可以在这里对pdf对象进行进一步操作
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19