【问题标题】:Angular PDFMake Dynamic Table with Nested JSON带有嵌套 JSON 的 Angular PDFMake 动态表
【发布时间】:2021-11-25 16:58:17
【问题描述】:

我使用了在这里找到的代码Building table dynamically with PDFMake,它可以完美地处理来自 API 的动态数据。但我的问题是嵌套 JSON。

这是 JSON 的样子:

dataseries":[
      {
         "timepoint":3,
         "cloudcover":2,
         "seeing":6,
         "transparency":2,
         "lifted_index":10,
         "rh2m":2,
         "wind10m":{
            "direction":"N",
            "speed":2
         },
         "temp2m":23,
         "prec_type":"none"
      },
      {
         "timepoint":6,
         "cloudcover":2,
         "seeing":6,
         "transparency":2,
         "lifted_index":15,
         "rh2m":3,
         "wind10m":{
            "direction":"N",
            "speed":2
         },
         "temp2m":21,
         "prec_type":"none"
      },

我正在尝试生成 wind10m 的内容,特别是 PDF 文件上的 directionspeed。如何访问和生成两个不同的 directionspeed 列?

这是我的 stackblitz 演示:https://stackblitz.com/edit/angular-ojgxtj?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

  • 我看到了你的 cmets,我更新了我的答案。如果这解决了你的问题,请点赞。谢谢

标签: angular typescript pdfmake


【解决方案1】:

您应该使用 JSON.stringify 而不是 .toString()

JSON.stringify() 方法将 JavaScript 值转换为 JSON 字符串,

如果指定了替换函数,则可选地替换值,或者如果指定了替换器数组,则可选地仅包括指定的属性。

发件人:

dataRow.push(row[column].toString());

dataRow.push(JSON.stringify(row[column]));

更新嵌套的 wind10m 列:

您需要将 colSpan 和 rowSpan 属性添加到表格行。

Stackblitz

  buildTableBody(data, columns, c2) {
    var body = [];

    //push first and second row
    body.push(columns);
    body.push(c2);
    data.forEach(function (row) {
      var dataRow = [];
      columns.forEach(function (column) {
        if (column.text == 'timepoint' || column.text == 'cloudcover') {
          dataRow.push(JSON.stringify(row[column.text]));
        } else if (column.text == 'wind10m') {
          dataRow.push(row['wind10m']['direction']);
        } else {
          dataRow.push(row['wind10m']['speed']);
        }
      });
      body.push(dataRow);
    });

    return body;
  }

  generatePdf() {
    console.log('generatePdf');

    let docDefinition = {
      content: [
        { text: 'PDF Generate', style: 'header' },
        this.table(
          this.holder,
          //first row
          [
            { text: 'timepoint', rowSpan: 2 },
            { text: 'cloudcover', rowSpan: 2 },
            { text: 'wind10m', colSpan: 2 },
            '',
          ],
          //second row
          [
            '',
            '',
            { text: 'direction' },
            { text: 'Speed' },
          ]
        ),
      ],
    };
    pdfmake.createPdf(docDefinition).open();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多