Search code examples
phpcodeigniterpdfmake

Is it possible to sum a column with pdfmake library?


I want to sum a column to get grand total from a pdf file generated by pdfmake

Sample Data:

#ID ItemName Description          Unit  Qty  Amount    Subtotal
1   Mawe     Misumari ya ukuta    KG    10    3,000.00  30,000.00
2   Mawe     Misumari ya ukuta    PCS   10   50,000.00 500,000.00
3   Mawe     Kwa ajili ya misingi KG    20    3,000.00  60,000.00

So i want to sum the Subtotal Column with pdfmake during export and get something like

#ID ItemName Description          Unit  Qty  Amount    Subtotal
1   Mawe     Misumari ya ukuta    KG    10    3,000.00  30,000.00
2   Mawe     Misumari ya ukuta    PCS   10   50,000.00 500,000.00
3   Mawe     Kwa ajili ya misingi KG    20    3,000.00  60,000.00
-----------------------------------------------------------------
Total:                                                 590,000.00
-----------------------------------------------------------------

Any idea please.


Solution

  • Thanks guys, i've solved it i just used here is the solution i think it might help someone out there. Hope the code is readable and easy to understand. Thanks again.

    "footerCallback": function ( row, data, start, end, display ) {
                        var api = this.api(), data;
                        var intVal = function ( i ) {
                            return typeof i === 'string' ?
                                i.replace(/[\$,]/g, '')*1 :
                                typeof i === 'number' ?
                                    i : 0;
                        };
                        total = api
                            .column( 6 ) //Getting the column # i want to sum
                            .data()
                            .reduce( function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0 );
                        pageTotal = api
                            .column( 6, { page: 'current'} ) 
                            .data()
                            .reduce( function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0 );
                        $( api.column( 6 ).footer() ).html(
                            'TZS '+ pageTotal.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") +'/='+
                            '( TZS '+ total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") +'/= total)'
                        );
                    }