You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery将HTML表格数据动态绑定到pdfmake表格主体

解决方案

核心思路

要实现动态绑定选中列的表头和数据到pdfmake,分三步执行:

  • 收集选中列的索引
  • 提取对应表头的纯文本内容
  • 遍历表格行,筛选出选中列的单元格数据

具体实现代码

HTML 结构示例

<table id="dataTable">
  <thead>
    <tr>
      <th><input type="checkbox" class="col-select" checked> ID</th>
      <th><input type="checkbox" class="col-select" checked> 姓名</th>
      <th><input type="checkbox" class="col-select"> 年龄</th>
      <th><input type="checkbox" class="col-select" checked> 邮箱</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>张三</td>
      <td>28</td>
      <td>zhangsan@example.com</td>
    </tr>
    <tr>
      <td>2</td>
      <td>李四</td>
      <td>32</td>
      <td>lisi@example.com</td>
    </tr>
  </tbody>
</table>
<button id="exportBtn">导出选中列到PDF</button>

JavaScript 逻辑(结合jQuery与pdfmake)

$(document).ready(function() {
  $('#exportBtn').click(function() {
    // 1. 收集选中列的索引
    const selectedColIndexes = [];
    $('#dataTable thead .col-select:checked').each(function() {
      selectedColIndexes.push($(this).parent('th').index());
    });

    if (selectedColIndexes.length === 0) {
      alert('请至少选择一列');
      return;
    }

    // 2. 构建PDF表头(剔除复选框标签,保留纯文本)
    const pdfHeader = [];
    $('#dataTable thead th').each(function(index) {
      if (selectedColIndexes.includes(index)) {
        const headerText = $(this).text().trim().replace(/^\s*<input.*?>/g, '');
        pdfHeader.push(headerText);
      }
    });

    // 3. 构建PDF行数据(仅保留选中列的单元格内容)
    const pdfRows = [];
    $('#dataTable tbody tr').each(function() {
      const rowData = [];
      $(this).find('td').each(function(index) {
        if (selectedColIndexes.includes(index)) {
          rowData.push($(this).text().trim());
        }
      });
      pdfRows.push(rowData);
    });

    // 4. 配置pdfmake并生成PDF
    const docDefinition = {
      content: [
        {
          table: {
            headerRows: 1,
            body: [pdfHeader, ...pdfRows]
          }
        }
      ]
    };

    pdfMake.createPdf(docDefinition).open();
  });
});

关键代码说明

  • 选中列索引收集:通过表头复选框的状态,标记需要导出的列位置,避免后续提取错误数据
  • 表头处理:正则剔除复选框的HTML代码,确保PDF表头显示纯净的标题文本
  • 行数据筛选:遍历每一行时,仅保留选中列对应的单元格内容,组成符合pdfmake要求的二维数组格式
  • 最终绑定:将表头作为表格第一行,和所有行数据一起传入table.body,完成动态数据绑定并生成PDF

内容的提问来源于stack exchange,提问作者ashok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:55:16