如何在pdfmake中获取每页商品总金额并展示在页脚
pdfmake 每页商品金额合计展示在页脚实现方案
核心逻辑是提前拆分每页商品预计算合计,或者通过pdfmake的动态渲染钩子实时统计每页金额,再配合动态页脚函数取值展示即可,以下是两种适用不同场景的实现方式:
方案1:固定商品行高场景(实现最简单,性能最优)
如果你的商品表格单行高度固定,可提前计算每页最大可容纳的商品数量,提前拆分数据并预计算每页合计:
- 按每页最大商品数拆分全部商品数组
- 预生成每页合计的映射数组,索引对应页码(pdfmake默认页码从1开始)
- 在动态页脚函数中直接按当前页码取对应合计值
示例代码:
// 1. 预处理商品数据 const allProducts = [250, 300, 500, 150, 200, 100] // 你的所有商品价格数据 const perPageMaxCount = 3 // 每页最多展示3个商品 const pageTotalMap = [0] // 索引0占位,对应页码1的合计存在索引1的位置 const splitPageProducts = [] for (let i = 0; i < allProducts.length; i += perPageMaxCount) { const currentPageProducts = allProducts.slice(i, i + perPageMaxCount) splitPageProducts.push(currentPageProducts) // 计算当前页合计存入映射数组 pageTotalMap.push(currentPageProducts.reduce((sum, price) => sum + price, 0)) } // 2. 生成PDF配置 const docDefinition = { // 动态页脚 footer: function (currentPage) { return `Total ${pageTotalMap[currentPage] || 0}` }, content: [ // 生成每页的商品表格 ...splitPageProducts.map((pageProducts, index) => ({ table: { body: [ ['商品名称', '商品价格'], ...pageProducts.map(price => ['示例商品', price]) ] }, // 非最后一页加手动分页,避免多生成空白页 pageBreak: index === splitPageProducts.length - 1 ? '' : 'after' })) ] } // 3. 导出PDF pdfMake.createPdf(docDefinition).download('商品明细.pdf')
方案2:动态商品行高场景(适配行高不固定的情况)
如果商品存在多行描述、行高不固定无法提前计算每页容量,可使用pdfmake的runningSections特性实时统计每页金额:
- 给所有商品的价格单元格添加自定义
mark标记,用于识别金额字段 - 配置
runningSections的累加规则,每页渲染时自动累加当前页所有标记的金额,新页自动重置统计值 - 页脚直接读取实时统计的当前页合计值
示例代码:
const allProducts = [250, 300, 500, 150, 200, 100] // 你的所有商品价格数据 const docDefinition = { // 配置每页金额统计规则 runningSections: { currentPageTotal: { initialValue: 0, // 每次渲染元素时触发统计 update: function (currentTotal, renderElement) { // 识别到是商品价格字段就累加 if (renderElement.mark === 'productPrice') { return currentTotal + renderElement.text } return currentTotal }, // 新的一页开始时重置统计值为0 resetOnNewPage: true } }, // 动态页脚读取统计值 footer: function (currentPage, pageCount, sections) { return `Total ${sections.currentPageTotal || 0}` }, content: [ { table: { body: [ ['商品名称', '商品价格'], // 所有商品行,给价格字段加mark标记 ...allProducts.map(price => [ '可能会折行的长商品描述示例', { text: price, mark: 'productPrice' } ]) ] } } ] } pdfMake.createPdf(docDefinition).download('商品明细.pdf')
注意:
runningSections特性需要pdfmake 0.2.x及以上版本支持,使用旧版本的话可以先升级到官方稳定版再使用该方案。
内容的提问来源于stack exchange,提问作者NerdL AlMas
相关产品推荐
相关产品推荐

