Right aligning numbers in export to PDF and Print

Right aligning numbers in export to PDF and Print

anishanish Posts: 9Questions: 5Answers: 0

Using the new 'Buttons' extension, when i either print or export to PDF everything is left aligned, while I would like the numbers to be right aligned.
The fix i used to right align numbers was
Step 1) Register a new function in the button API, like so

DataTable.Api.register( 'buttons.getAlignmentForCols()', function ( dt, headers ) {
    var alignmentForCols = $.map( headers, function ( header ) {
        for(var i = 0; i < dt.settings()[0].aoColumns.length; i++){
            var column = dt.settings()[0].aoColumns[i];
            if(column.title == header){
                if(column.type == 'num' || column.type == 'num-fmt')
                    return 'right';
                return 'left';
            }
        }
    });
    return  alignmentForCols;

} );

Step 2) In the 'action' function for pdfHtml5 add the following
a) var alignmentForCols = dt.buttons.getAlignmentForCols(dt, data.header);
b) replace the following code

          rows.push( $.map( data.body[i], function ( d, index) {
         return {
            text: d,
            style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd',
                };
    } ) );

with

          rows.push( $.map( data.body[i], function ( d, index) {
                var alignment = alignmentForCols[index];
                return {
                    text: d,
                    style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd',
                    alignment: alignment
                };
    } ) );

Step 3) Do a similar thing for print
a) In the action function for print add
    var alignmentForCols = dt.buttons.getAlignmentForCols(dt,data.header);
b) Add the following code in the action function
      var addRowWithStyle = function ( d, tag ) {
        var str = '<tr>';
        for ( var i=0, ien=d.length ; i<ien ; i++ ) {
                           var style = 'text-align: ' + alignmentForCols[i];
            str += '<'+tag+' style="' + style + '">'+d[i]+'</'+tag+'>';
        }

        return str + '</tr>';
    };
and then replace
           for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
        html += addRow( data.body[i], 'td' );
    }
with
           for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
        html += addRowWithStyle( data.body[i], 'td' );
    }
This discussion has been closed.