夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • JavaScript文章

    • 33个非常实用的JavaScript一行代码
    • 实用JavaScricpt封装
    • ES5面向对象
    • ES6面向对象
    • 多种数组去重性能对比
    • 获取ip地址
    • ES6扩展符运用
    • file、base64和blob互相转化
    • 图片转base64格式
    • 弹窗的封装
    • websocket实现二维码扫描
    • 比typeof运算符更准确的类型判断
    • 前端下载excel文件
    • 数组与对象的互相转化
    • JS编码与转码
    • 树结构与扁平化相互转换
    • 实现微信登录
    • 常用表单验证
    • 在H5中实现OCR拍照识别身份证功能
    • 滚动条元素定位
    • 获取目标容器内的元素列表
    • 微信H5支付
    • js中的函数注释
    • 大模型流式数据前端实现
    • 定高虚拟列表
    • 不定高虚拟列表
    • 虚拟表格
    • 移动端文件预览
    • 浏览器缓存机制
    • 前端从剪切板获取word图片
    • 微信公众号调试
    • html导出pdf
      • 封装
      • 使用
    • node转化多语言
  • 前端架构

  • 学习笔记

  • 全栈项目

  • 前端
  • JavaScript文章
夜猫子
2024-08-23
目录

html导出pdf

# 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

# 使用

// 获取要导出的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
编辑 (opens new window)
上次更新: 2025/9/10 18:17:04
微信公众号调试
node转化多语言

← 微信公众号调试 node转化多语言→

最近更新
01
H5调用微信jssdk
09-28
02
VueVirtualScroller
09-19
03
IoC 解决了什么痛点问题?
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式