首页 文章

jspdf autoTable中的动态单元格颜色?

提问于
浏览
0

是否可以使用映射到表的对象的嵌套属性来定义单元格颜色?

对象的JSON结构是:

objects: [
{
  "agent": "agent_1",
  "days": {
     day_0: {
       "code": "ABC",
       "color": "#0062cc"
     },
     day_1: {
       "code": "DEF",
       "color": "#a09494b2"
     }
  },
  {
  [...]
  }
]

我有一个像这样定义的表:

let columns = [
  {title: "Agent", dataKey: "agent"},
  {title: "january 1st", dataKey: "day_0"},
  {title: "january 2nd", dataKey: "day_1"}]

let rows = [
  {agent: "agent_1", day_0: "ABC", day_1: "DEF"},
  [...]
]

一切正常 . 但我想动态设置每天单元格的颜色,使用相应对象的颜色代码进行设置 . 就像是 :

createdCell: function(cell, data) {
  {
     cell.styles.fillColor = "day_0.color";
  }
}

但我无法想象如何将数据传递给表 . 可能吗 ?可以 displayProperty 以任何方式提供帮助吗?

1 回答

  • 0

    编辑:在这种情况下,需要jspdf-autotable的v2.3.4

    根据我们的评论讨论,我想我理解你的问题 . 你可以尝试这样的东西(使用here中的hexToRgb函数)

    let columns = [{
        title: "Agent",
        dataKey: "agent"
      },
      {
        title: "january 1st",
        dataKey: "day_0"
      },
      {
        title: "january 2nd",
        dataKey: "day_1"
      }
    ]
    
    let objects = [{
      agent: "agent_1",
      day_0: {
        "code": "ABC",
        "color": "#00ff00"
      },
      day_1: {
        "code": "DEF",
        "color": "#ff0000"
      }
      // etc
    }];
    
    let doc = jsPDF()
    doc.autoTable(columns, objects, {
      createdCell: function(cell, data) {
        let hex = cell.raw.color
        if (hex) {
          let rgb = hexToRgb(hex)
          cell.styles.fillColor = rgb;
          cell.text = cell.raw.code
        }
      }
    });
    doc.save('jhg.pdf')
    
    function hexToRgb(hex) {
        var bigint = parseInt(hex.replace('#', ''), 16);
        var r = (bigint >> 16) & 255;
        var g = (bigint >> 8) & 255;
        var b = bigint & 255;
        return [r, g, b];
    }
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.4/jspdf.plugin.autotable.js"></script>
    

相关问题