如何在Angular中使用pdfMake.js合并多组内容生成单个PDF
错误原因
你遇到的报错是语法层面的问题:JavaScript 不允许在数组字面量([]包裹的数组定义结构)中直接插入for循环语句。
解决方案
你可以提前构建好content内容数组,再赋值给docDefinition的content字段,以下是两种可行写法:
写法1:使用flatMap(适配现代JS环境)
直接用数组的flatMap方法遍历生成每个检验单对应的内容块:
this.docDefinition = { pageSize: 'LETTER', pageOrientation: 'landscape', pageMargins: [40, 30, 40, 30], header: function (page, pages) { return { height: 14, text: 'Sample', style: 'titleHeader', alignment: 'center' }; }, // 直接用flatMap生成content数组 content: selectedLabOrders.flatMap(labOrder => [ this.buildSectionPatientInfo(), { table: { widths: ['50%', '50%'], headerRows: 0, body: [ [ // 右侧内容 [ this.buildSectionLabInfo(), this.buildSectionLabUseOnly() ], // 左侧内容 [ this.buildSectionFrame(), this.buildSectionSpecialInstructionsLab() ] ] ] }, layout: 'noBorders' }, // 若需要每个检验单单独分页,保留下面这行,不需要可删除 { text: '', pageBreak: 'after' } ]), styles: { titleHeader: { fontSize: 16, bold: true, margin: [0, 10, 0, 0], }, tableHeader: { bold: true, fontSize: 13, color: 'black' } }, defaultStyle: { fontSize: 9, lineHeight: .9 } }; try { pdfMake.createPdf(this.docDefinition).open(); } catch (e) { alert(e.toString()); }
写法2:for循环提前构建数组(兼容所有环境)
如果运行环境不支持flatMap,可以先声明空数组循环push内容:
// 提前构建content数组 const pdfContent = []; for (const labOrder of selectedLabOrders) { // 如果你的方法需要用到当前labOrder的数据,调用时记得传入参数:this.buildSectionPatientInfo(labOrder) pdfContent.push(this.buildSectionPatientInfo()); pdfContent.push({ table: { widths: ['50%', '50%'], headerRows: 0, body: [ [ [ this.buildSectionLabInfo(), this.buildSectionLabUseOnly() ], [ this.buildSectionFrame(), this.buildSectionSpecialInstructionsLab() ] ] ] }, layout: 'noBorders' }); // 每个检验单单独分页保留,不需要可删除 pdfContent.push({ text: '', pageBreak: 'after' }); } // 赋值给docDefinition this.docDefinition = { pageSize: 'LETTER', pageOrientation: 'landscape', pageMargins: [40, 30, 40, 30], header: function (page, pages) { return { height: 14, text: 'Sample', style: 'titleHeader', alignment: 'center' }; }, content: pdfContent, styles: { titleHeader: { fontSize: 16, bold: true, margin: [0, 10, 0, 0], }, tableHeader: { bold: true, fontSize: 13, color: 'black' } }, defaultStyle: { fontSize: 9, lineHeight: .9 } }; try { pdfMake.createPdf(this.docDefinition).open(); } catch (e) { alert(e.toString()); }
注意事项
如果你的buildSectionXXX系列方法需要用到当前遍历的检验单数据,调用时将labOrder作为参数传入即可。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

