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

使用PDFMake导出多表格PDF时添加自定义标题及间距的需求

解决方案

要实现你需要的两个优化,只需对JavaScript代码中的表格内容组装部分做两处修改即可,以下是完整的实现代码:

修改后的JavaScript代码

$(document).ready( function() {
    var tables  = document.querySelectorAll('.data-table');
    var tableArr = [];
    var tableContent = [];

    tables.forEach((element, index) => {
      $(element).DataTable();
      tableArr.push(element.dataset.sheetname);
    });

    $('#ExportPdf').click(function(){
      var config = {
        className:"buttons-pdf buttons-html5",
        customize:null,
        download:"download",
        exportOptions:{
          format: {
            header: function (data, column, node){
              if(node.dataset.exportname != null){
                return node.dataset.exportname;
              }
              return data;
            },
            body: function (data, row, column, node) {
              if(node.dataset.exportname != null){
                return node.dataset.exportname;
              }
              return data;
            }
          }
        },
        extension:".pdf",
        filename:"*",
        header:true,
        namespace:".dt-button-2",
        orientation:"portrait",
        pageSize:"A4",
        title:"*"
      };

      var tablesConverted = {};

      tables.forEach((element, index) => {
        var dataTable = $(element).DataTable();
        var data = dataTable.buttons.exportData( config.exportOptions );
        var info = dataTable.buttons.exportInfo( config );
        var rows = [];
        
        if (config.header) {
          rows.push($.map(data.header, function (d) {
            return {
              text: typeof d === 'string' ? d : d+'',
              style: 'tableHeader'
            };
          }));
        }

        for (var i=0, ien=data.body.length ; i<ien ; i++ ) {
          rows.push($.map(data.body[i], function ( d ) {
            return {
              text: typeof d === 'string' ? d : d+'',
              style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd'
            };
          }));
        }

        // 添加表格标题(使用data-sheetname属性值)
        tableContent.push({
          text: element.dataset.sheetname,
          style: 'tableTitle',
          margin: [0, 0, 0, 10]
        });
        
        // 添加表格并设置底部间距
        tableContent.push({
          table: {
            headerRows: 1,
            body: rows,
          },
          layout: "lightHorizontalLines",
          margin: [0, 0, 0, 20]
        });
      });

      var doc = {
        pageSize: config.pageSize,
        pageOrientation: config.orientation,
        content: tableContent,
        styles: {
          tableHeader: {
            bold: true,
            fontSize: 11,
            color: 'white',
            fillColor: '#2d4154',
            alignment: 'left',

          },
          tableBodyEven: {},
          tableBodyOdd: {
            fillColor: '#f3f3f3'
          },
          tableFooter: {
            bold: true,
            fontSize: 11,
            color: 'white',
            fillColor: '#2d4154'
          },
          title: {
            alignment: 'center',
            fontSize: 15
          },
          // 新增表格标题样式
          tableTitle: {
            bold: true,
            fontSize: 13,
            alignment: 'left'
          },
          message: {}
        },
        defaultStyle: {
          fontSize: 10
        }
      };

      // 调整第一个标题的顶部间距,避免紧贴页面顶部
      if(tableContent.length > 0){
        tableContent[0].margin = [0, 20, 0, 10];
      }

      if ( config.customize ) {
        config.customize( doc, config );
      }
      pdfMake.createPdf(doc).download('optionalName.pdf');
    });
  });

关键修改说明

  1. 添加表格标题:

    • 循环处理每个表格时,先向tableContent数组中插入一个文本对象,内容直接取当前表格的data-sheetname属性值。
    • 在styles中新增tableTitle样式,设置标题的字体大小、加粗、对齐方式,让标题更醒目易区分。
  2. 添加表格间间距:

    • 给每个表格对象添加margin属性,设置底部间距为20pt,让后续表格和前一个表格保持空白间隔。
    • 给标题设置底部间距,确保标题和下方表格的距离合适,不会显得拥挤。

其他代码(CSS和HTML无需修改)

CSS代码

<style>
  table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }

  td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
  }

  tr:nth-child(even) {
    background-color: #dddddd;
  }
</style>

HTML代码

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<!-- Body -->
<button id="ExportPdf" type="button">Export All</button>
<table class="data-table" data-sheetname="Table 1" id="table-1">
  <thead>
    <tr>
      <th data-exportname="Company">Company1</th>
      <th data-exportname="Contact">Contact1</th>
      <th data-exportname="Country">Country1</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-exportname="Alfreds Futterkiste">Alfreds Futterkiste</td>
      <td data-exportname="Maria Anders">Maria Anders</td>
      <td data-exportname="Germany">Germany</td>
    </tr>
    <tr>
      <td data-exportname="Centro comercial Moctezuma">Centro comercial Moctezuma</td>
      <td data-exportname="Francisco Chang">Francisco Chang</td>
      <td data-exportname="Mexico">Mexico</td>
    </tr>
    <tr>
      <td data-exportname="Ernst Handel">Ernst Handel</td>
      <td data-exportname="Roland Mendel">Roland Mendel</td>
      <td data-exportname="Austria">Austria</td>
    </tr>
  </tbody>
</table>
<br>
<table class="data-table" data-sheetname="Table 2">
  <thead>
    <tr>
      <th data-exportname="Company">Company</th>
      <th data-exportname="Contact">Contact</th>
      <th data-exportname="Country">Country</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-exportname="Alfreds Futterkiste">Alfreds Futterkiste</td>
      <td data-exportname="Maria Anders">Maria Anders</td>
      <td data-exportname="Germany">Germany</td>
    </tr>
  </tbody>
</table>
<br>
<table class="data-table" data-sheetname="Table 3">
  <thead>
    <tr>
      <th data-exportname="Company">Company</th>
      <th data-exportname="Contact">Contact</th>
      <th data-exportname="Country">Country</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-exportname="Centro comercial Moctezuma">Centro comercial Moctezuma</td>
      <td data-exportname="Francisco Chang">Francisco Chang</td>
      <td data-exportname="Mexico">Mexico</td>
    </tr>
    <tr>
      <td data-exportname="Ernst Handel">Ernst Handel</td>
      <td data-exportname="Roland Mendel">Roland Mendel</td>
      <td data-exportname="Austria">Austria</td>
    </tr>
  </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:40:00