Search code examples
javascriptdatatablespdf-generation

Is there an option to right align text in messageBottom attribute of DataTables pdf export?


I've created a pdf export using Datatables and I am displaying a message under the exported table using messageBottom. The problem is that it is automatically left aligned, and I would like the value to be right aligned, underneath the last column of the exported table. Is there a way to achieve this? I've looked through the Datatable pdfHtml5 documentation but I can't seem to figure out how to adjust the alignment of text in messageBottom or messageTop.

Here is my code initializing the table:

var table = $('#exampleTable').DataTable( {
        dom: 'Bfrtip',
        buttons: [
         {
            extend: 'pdfHtml5',
            messageBottom: function() {
               return 'message to be displayed at bottom'
            },
            customize: function ( doc ) {
            /* here I am aligning text in a column to the right */
            var rowCount = table.rows().count() + 1;
            for (i = 0; i < rowCount; i++) {
               doc.content[2].table.body[i][3].alignment = 'right';
            };
         }
      }
   ]
} );

Solution

  • in the version of datable that I am using I have solved it this way. 'messageBottom' uses the style 'message', so adding the following line in the customize has solved the problem for me.

    doc.styles.message.alignment = "right";
    

    The problem with this solution is that 'messageTop' also uses the style 'message' so it will also align to the right but in my case I am only using 'messageBottom'. I don't know if there is a better way.

    My example:

    {
        extend: 'pdf',
        messageBottom: function() { 
            return "\n\nTOTAL VENCIMIENTO: "+$('#header-vcto-total span').text()+"\n"
        },
        customize: function(doc) {
            /** this line changes the alignment of 'messageBottom' and 'messageTop' **/
            doc.styles.message.alignment = "right";
    
            doc.content[1].table.widths = [ '40%',  '25%', '17.5%', '17.5%'];
            var rowCount = doc.content[1].table.body.length;
            for (i = 1; i < rowCount; i++) {
                doc.content[1].table.body[i][1].alignment = 'center';
                doc.content[1].table.body[i][2].alignment = 'center';
                doc.content[1].table.body[i][3].alignment = 'right';
                doc.content[1].table.body[i][3].text += ' €';
            };
        }    
    }
    

    I hope you find it useful. A greeting.