如何移动表导出pdfhtml5数据表?

问题描述 投票:3回答:1

我想使用pdfhtml和我的代码导出数据表

$(document).ready(function() {
   $('#example').DataTable( {
      dom: 'Bfrtip',
         buttons: [ {
            extend: 'pdfHtml5',
            text: 'PDF with image'
         } ]
    } );
} );

和结果导出pdf像这样

enter image description here如何将桌子移到中心?我可以修改这个布局吗?

jquery pdf datatables
1个回答
3
投票

您可以使用customize回调来更改生成的PDF的布局。它没有那么好记录(但是,我猜)但是请参阅PDFMake definition object docs以了解命名和对象结构,并查看this answer(由我)作为一个非常简单的示例。

AFAIK没有任何选项可以让你强制整个内容的中心(即一种docDefinition.content.align或类似),但你可以否决页面边距和列宽。

$('#example').DataTable({
    dom: 'Bfrtip',
    buttons: [ {
       extend: 'pdfHtml5',
       text: 'PDF with image',
       customize: function(doc) {
          //pageMargins [left, top, right, bottom] 
          doc.pageMargins = [ 150, 20, 150, 20 ];
       }
    }]
});

这将有效地在每个页面上创建150px的左/右边距,使表格居中。现在您只需要找出最适合您需求的边距尺寸。在该过程中,您可能还需要强制导出列的宽度:

$('#example').DataTable( {
    dom: 'Bfrtip',
    buttons: [{
       extend: 'pdfHtml5',
       text: 'PDF with image',
       customize: function(doc) {
          doc.content.forEach(function(item) {
             if (item.table) {
                // Set width for 3 columns
                item.table.widths = [100, 40, '*'] 
             } 
          });
       }
    }]
});

我正在迭代content数组,因为我们无法确定哪个索引保持table属性。上面简单地设置了一个导出的三列布局,以具有100px40px和“其余”宽度。如果要将宽度调整为内容,请使用'auto'。请注意,如果您的item.table.widths与表中的列数不完全匹配,则导出将失败。

无论如何 - 通过定义pageMargin并且可能稍微调整一些列的宽度,您应该能够非常容易地创建居中的PDF。

© www.soinside.com 2019 - 2024. All rights reserved.