How to add the complex headers to pdfmaker export options using datatables?

How to add the complex headers to pdfmaker export options using datatables?

cris19ncris19n Posts: 55Questions: 18Answers: 0

I am using pdfmaker and datatables. What I want is that when any export file is generated, I also take the first two rows ADMINISTER USERS and USER DATA, which is covering two items (last login and actions).

Because it is only taking the row (third row) of each item: this is an example when I click on pdf view, it takes the title but not the first two rows of the table.

How can I add the other headers to my export options (copy, excel, pdf, vistapdf).

Also, how do I choose which fields I want me to take when exporting a file because as STATUS AND ACTIONS are button fields, in the final file the fields are left blank, so I don't want it to take them.

this is my js code, where I start the table and apply the pdfmaker settings:

var table = $('#search_user').DataTable( {
        dom: 'Blftipr',
        buttons:[
            {
                extend:    'copy',
                text:      '<i class="fa  fa-copy"></i> ',
                title: tittleoage,
                titleAttr: 'Exportar a Excel',
                className: 'btn btn-success'
            },
            {
                extend:    'excelHtml5',
                text:      '<i class="fa fa-file-excel-o"></i> ',
                title: tittleoage,
                titleAttr: 'Exportar a Excel',
                className: 'btn btn-success'
            },
            {
                extend:    'pdfHtml5',
                text:      '<i class="fa fa-file-pdf-o"></i> ',
                title: tittleoage,
                titleAttr: 'Exportar a PDF',
                className: 'btn btn-danger'
            },
            {
                extend:    'print',
                text:      '<i class="fa fa-print"></i> ',
                title: tittleoage,
                titleAttr: 'Imprimir',
                className: 'btn btn-info'
            },
        ],
        "language": {

        "sProcessing":     "PROCESANDO...",
        "sLengthMenu":     "MOSTRAR _MENU_ REGISTROS",
        "sZeroRecords":    "NO SE ENCONTRARON RESULTADOS",
        "sEmptyTable":     "Ningún dato disponible en esta tabla",
        "sInfo":           "MOSTRANDO REGISTROS DEL _START_ AL _END_ DE UN TOTAL DE _TOTAL_",
        "sInfoEmpty":      "MOSTRANDO REGISTROS DEL 0 AL 0 DE UN TOTAL DE 0",
        "sInfoFiltered":   "(FILTRADO DE UN TOTAL DE _MAX_ REGISTROS)",
        "sInfoPostFix":    "",
        "sSearch":         "BUSCAR:",
        "sUrl":            "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "CARGANDO...",
        "oPaginate": {
        "sFirst":    "PRIMERO",
        "sLast":     "ULTIMO",
        "sNext":     "SIGUIENTE",
        "sPrevious": "ANTERIOR"
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        }

    },
    columnDefs: [
        {
            targets: -9,
            className: 'dt-body-right'
        }
      ],
      /*aquí estoy filtrando las columnas de donde obtendré los datos cuando se escribe algo en el buscador*/
    columnDefs: [
        { targets: [1, 2, 4, 6, 7], searchable: true},
        { targets: '_all', searchable: false }
    ]
    } );

Replies

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    This thread should help, it's asking the same thing.

    Cheers,

    Colin

  • cris19ncris19n Posts: 55Questions: 18Answers: 0

    I have not been able to implement the other codes in mine, because I am currently using the latest versions that offer data tables, I don't know what I should modify, so that it supports colpsan and rowspan, on top of that so that the seldas are combined when I export in excel , pdf, printf, etc. please help.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    That's not something that's currently supported, I'm afraid, so you'll need to implement that fix into the version of the code you're using. And likewise for the other exports, that'll be different for each due to the third-party packages being used.

    Colin

  • cris19ncris19n Posts: 55Questions: 18Answers: 0

    Could you help me with this code to generate pdf with headers that supports colspan, it only takes the first and last header, I don't know exactly how to make it take all the headers I have.

     $(document).ready(function() {
            $('#dataTable').DataTable({
              dom: 'Bfrtip',
              buttons: [
                'copy', {
                  extend: 'csv',
                  "download": "download"
                }, {
                  extend: 'excel',
                  "download": 'download'
                }, {
                  extend: 'pdf',
                  text: 'Export with two row headers',
                  download: 'download',
                  customize: function(pdfDocument) {
                    pdfDocument.content[1].table.headerRows = 2;
                    var firstHeaderRow = [];
                    $('#dataTable').find("thead>tr:first-child>th").each(
                      function(index, element) {
                        var colSpan = element.getAttribute("colSpan");
                        firstHeaderRow.push({
                          text: element.innerHTML,
                          style: "tableHeader",
                          colSpan: colSpan
                        });
                        for (var i = 0; i < colSpan - 1; i++) {
                          firstHeaderRow.push({});
                        }
                      });
                    pdfDocument.content[1].table.body.unshift(firstHeaderRow);
    
                  }
                }, {
                  extend: 'print',
                  download: 'download'
                }
              ]
            });
          });
    

    my headers:

    <thead>
              <tr>
                 <th colspan="9" class="info text-center">ADMINS USERS</th>
              </tr>
              <tr>
                  <th colspan="6" class="info text-center"></th>
                  <th colspan="2" class="info text-center">DATOS USERS</th>
                  <th colspan="1" class="info text-center"></th>
              </tr>
              <tr class="info">
                  <th style="width:2%; color: #1E90FF;">#</th>
                  <th style="width:10%; color: #1E90FF;">NOMBRE</th>
                  <th style="width:9%; color: #1E90FF;">USUARIO</th>
                  <th style="color: #1E90FF;">FOTO</th>
                  <th style="color: #1E90FF;">TIPO USUARIO</th>
                  <th style="color: #1E90FF;">ESTADO</th>
                  <th style="color: #1E90FF;">FECHA DE REGISTRO</th>
                  <th style="color: #1E90FF;">ULTIMO LOGIN</th>
                  <th style="width:9%; color: #1E90FF;">ACCIONES</th>
           </tr>
    </thead>
    
  • cris19ncris19n Posts: 55Questions: 18Answers: 0

    help! @colin

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    You will need to create a loop to loop through each thead row. In that loop then loop through each th to get the html, colspan, etc that you want. Here is a simple example to show how you can loop through multiple headers.
    http://live.datatables.net/kucayicu/1/edit

    Kevin

  • cris19ncris19n Posts: 55Questions: 18Answers: 0

    There is a solution that works for me to export files in Excel or other formats, including their headers:

    https://examples.bootstrap-table.com/index.html?bootstrap3

  • TrinavTrinav Posts: 4Questions: 0Answers: 0

    I have used the above code to download in pdf format.The code is working fine it displays n number of header while we download but am facing the issues the header will display div class e.g.,div class="" style="height:
    0px; overflow:
    hidden;">Month</div>
    I dont know how to rectify this please help me to solve this problem.!
    image

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    @Trinav Its hard to say what is wrong without seeing the problem. Start by debugging the code you are using to get the header information to see what needs to change. Possibly you are using jQuery html() but should be using jQuery text() instead. If you still need help please provide a running test case replicating the issue so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • TrinavTrinav Posts: 4Questions: 0Answers: 0

    {
    extend: 'pdf', download: 'open',
    pageSize : 'A1',orientation: 'landscape',

             customize: function(pdfDocument) {
          let headerRows = [];
          let noOfColumn = 16;
          let rowSpansOfColumns = [];
          for (let i = 0; i < noOfColumn; i++) {
            rowSpansOfColumns.push([]);
          }
          let noOfExtraHeaderRow = 3;
          pdfDocument.content[1].table.headerRows = noOfExtraHeaderRow + 1;
          for (let i = 1; i <= noOfExtraHeaderRow; i++) {
            let headerRow = [];
            let colIdx = 0;
            while (colIdx < rowSpansOfColumns.length && rowSpansOfColumns[colIdx].includes(i)) {
              headerRow.push({});
              colIdx++
            }
    
            $('#kt_datatable_example_1').find("thead>tr:nth-child(" + i + ")>th").each(
              function(index, element) {
                let colSpan = parseInt(element.getAttribute("colSpan"));
                let rowSpan = parseInt(element.getAttribute("rowSpan"));
                if (rowSpan > 1) {
                  for (let col = colIdx; col < colIdx + colSpan; col++) {
                    for (let row = i + 1; row < i + rowSpan; row++) {
                      rowSpansOfColumns[col].push(row);
                    }
                  }
                }
                headerRow.push({
                  text: element.innerHTML,
                  style: "tableHeader",
                  colSpan: colSpan,
                  rowSpan: rowSpan
                });
                colIdx++
                for (let j = 0; j < colSpan - 1; j++) {
                  headerRow.push({});
                  colIdx++
                }
                while (colIdx < rowSpansOfColumns.length && rowSpansOfColumns[colIdx].includes(i)) {
                  headerRow.push({});
                  colIdx++
                }
              });
    
            headerRows.push(headerRow);
          }
          for (let i = 0; i < headerRows.length; i++) {
            pdfDocument.content[1].table.body.unshift(headerRows[headerRows.length - 1 - i]);
          }
        } }
    

    This is my code
    am included datatable bundle.js script

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    Maybe you will want to use text: element.innerText, instead of text: element.innerHTML, on line 30. See this SO Thread for more details. If this doesn't help please provide a running test case showing the problem so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • TrinavTrinav Posts: 4Questions: 0Answers: 0

    Thank you so much i got the result.
    Do you have any idea to download in excel and csv format for this three header form.

Sign In or Register to comment.