React中使用jsPDF导出PDF时如何实现每页重复指定头部元素
React+jsPDF实现每页重复固定头部导出PDF方案
前置准备
先安装所需依赖:npm install jspdf html2canvas
核心实现代码
替换你业务中的saveDiv函数即可:
import jsPDF from 'jspdf'; import html2canvas from 'html2canvas'; const saveDiv = async () => { // 初始化PDF:参数依次为 方向(l横向/p纵向)、单位、纸张尺寸 const pdf = new jsPDF('l', 'mm', 'a4'); const pdfPageWidth = pdf.internal.pageSize.getWidth(); const pdfPageHeight = pdf.internal.pageSize.getHeight(); // 转换固定头部为画布,缓存复用 const headerDom = document.getElementById('id1'); const headerCanvas = await html2canvas(headerDom, { scale: 2, useCORS: true }); // 计算头部在PDF内的适配高度(按PDF宽度等比例缩放,避免变形) const headerPdfHeight = (headerCanvas.height * pdfPageWidth) / headerCanvas.width; // 转换主体内容为画布 const contentDom = document.getElementById('id2'); const contentCanvas = await html2canvas(contentDom, { scale: 2, useCORS: true }); // 计算内容在PDF内的适配总高度 const contentTotalPdfHeight = (contentCanvas.height * pdfPageWidth) / contentCanvas.width; // 单页可容纳的内容高度 = 单页总高度 - 头部高度 const singlePageContentHeight = pdfPageHeight - headerPdfHeight; // 计算总分页数 const totalPageNum = Math.ceil(contentTotalPdfHeight / singlePageContentHeight); let contentOffset = 0; for (let pageIndex = 0; pageIndex < totalPageNum; pageIndex++) { // 非第一页新增空白页 if (pageIndex !== 0) { pdf.addPage(); } // 每页先渲染固定头部 pdf.addImage(headerCanvas, 'PNG', 0, 0, pdfPageWidth, headerPdfHeight); // 渲染当前页对应内容段 pdf.addImage( contentCanvas, 'PNG', 0, headerPdfHeight - contentOffset, pdfPageWidth, contentTotalPdfHeight ); // 偏移量累加,下一页展示后续内容 contentOffset += singlePageContentHeight; } // 导出文件 pdf.save('导出结果.pdf'); };
可调参数说明
- 若不需要横向PDF,可将
new jsPDF的第一个参数改为'p'切换为纵向 scale参数控制导出清晰度,数值越高越清晰,导出文件体积也越大- 若不想用A4尺寸,可将
new jsPDF的第三个参数改为自定义数组,比如[2000, 3000]自定义宽高适配你的DOM尺寸
内容的提问来源于stack exchange,提问作者JohnWick
相关产品推荐
相关产品推荐

