ONE BUTTO PRINT

ONE BUTTO PRINT

lauromnetolauromneto Posts: 129Questions: 0Answers: 0

Good afternoon.
I managed to generate the XLS and PDF generation of 2 datatables in 1 single file.
Would anyone know to say, how to make the print (print button) perform the same task!? In other words, using a single PRINT button to print 2 datatables!

Replies

  • montoyammontoyam Posts: 568Questions: 136Answers: 5
    edited July 2020

    sorry, I don't have an answer for you, but can you share your XLS/PDF code? I am needing to do that as well.

    ahhh.. sorry, I saw your other post after I already posted this comment.
    https://datatables.net/forums/discussion/63479/export-pdf#latest

  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0

    Olá.
    O código do PDF você já conseguiu pegar né?

    Abaixo o código do XLS. Este tem que ser antes de inicializar a datatable:

                function getHeaderNames(table) {
                    // Gets header names.
                    //params:
                    //  table: table ID.
                    //Returns:
                    //  Array of column header names.
    
                    var header = $(table).DataTable().columns().header().toArray();
    
                    var names = [];
                    header.forEach(function(th) {
                    names.push($(th).html());
                    });
                    return names;
                }
    
                function buildCols(data) {
                    // Builds cols XML.
                    //To do: deifne widths for each column.
                    //Params:
                    //  data: row data.
                    //Returns:
                    //  String of XML formatted column widths.
    
                    var cols = '<cols>';
    
                    for (i=0; i<data.length; i++) {
                        colNum = i + 1;
                        cols += '<col min="' + colNum + '" max="' + colNum + '" width="20" customWidth="1"/>';
                    }
    
                    cols += '</cols>';
    
                    return cols;
                }
    
                function buildRow(data, rowNum, styleNum) {
                    // Builds row XML.
                    //Params:
                    //  data: Row data.
                    //  rowNum: Excel row number.
                    //  styleNum: style number or empty string for no style.
                    //Returns:
                    //  String of XML formatted row.
    
                    var style = styleNum ? ' s="' + styleNum + '"' : '';
    
                    var row = '<row r="' + rowNum + '">';
    
                    for (i=0; i<data.length; i++) {
                        colNum = (i + 10).toString(36).toUpperCase();  // Convert to alpha
    
                        var cr = colNum + rowNum;
    
                        row += '<c t="inlineStr" r="' + cr + '"' + style + '>' +
                        '<is>' +
                        '<t>' + data[i] + '</t>' +
                        '</is>' +
                        '</c>';
                    }
    
                    row += '</row>';
    
                    return row;
                }
    
                function getTableData(table, title) {
                    // Processes Datatable row data to build sheet.
                    //Params:
                    //  table: table ID.
                    //  title: Title displayed at top of SS or empty str for no title.
                    //Returns:
                    //  String of XML formatted worksheet.
    
                    var header = getHeaderNames(table);
                    var table = $(table).DataTable();
                    var rowNum = 1;
                    var mergeCells = '';
                    var ws = '';
    
                    ws += buildCols(header);
                    ws += '<sheetData>';
    
                    if (title.length > 0) {
                        ws += buildRow([title], rowNum, 51);
                        rowNum++;
    
                        mergeCol = ((header.length - 1) + 10).toString(36).toUpperCase();
    
                        mergeCells = '<mergeCells count="1">'+
                        '<mergeCell ref="A1:' + mergeCol + '1"/>' +
                        '</mergeCells>';
                    }
    
                    ws += buildRow(header, rowNum, 2);
                    rowNum++;
    
                    // Loop through each row to append to sheet.    
                    table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
                        var data = this.data();
    
                        // If data is object based then it needs to be converted 
                        // to an array before sending to buildRow()
                        ws += buildRow(data, rowNum, '');
    
                        rowNum++;
                    } );
    
                    ws += '</sheetData>' + mergeCells;
    
                    return ws;
    
                }
    
                function setSheetName(xlsx, name) {
                    // Changes tab title for sheet.
                    //Params:
                    //  xlsx: xlxs worksheet object.
                    //  name: name for sheet.
    
                    if (name.length > 0) {
                        var source = xlsx.xl['workbook.xml'].getElementsByTagName('sheet')[0];
                        source.setAttribute('name', name);
                    }
                }
    
                function addSheet(xlsx, table, title, name, sheetId) {
                    //Clones sheet from Sheet1 to build new sheet.
                    //Params:
                    //  xlsx: xlsx object.
                    //  table: table ID.
                    //  title: Title for top row or blank if no title.
                    //  name: Name of new sheet.
                    //  sheetId: string containing sheetId for new sheet.
                    //Returns:
                    //  Updated sheet object.
    
                    //Add sheet2 to [Content_Types].xml => <Types>
                    //============================================
                    var source = xlsx['[Content_Types].xml'].getElementsByTagName('Override')[1];
                    var clone = source.cloneNode(true);
                    clone.setAttribute('PartName','/xl/worksheets/sheet2.xml');
                    xlsx['[Content_Types].xml'].getElementsByTagName('Types')[0].appendChild(clone);
    
                    //Add sheet relationship to xl/_rels/workbook.xml.rels => Relationships
                    //=====================================================================
                    var source = xlsx.xl._rels['workbook.xml.rels'].getElementsByTagName('Relationship')[0];
                    var clone = source.cloneNode(true);
                    clone.setAttribute('Id','rId3');
                    clone.setAttribute('Target','worksheets/sheet2.xml');
                    xlsx.xl._rels['workbook.xml.rels'].getElementsByTagName('Relationships')[0].appendChild(clone);
    
                    //Add second sheet to xl/workbook.xml => <workbook><sheets>
                    //=========================================================
                    var source = xlsx.xl['workbook.xml'].getElementsByTagName('sheet')[0];
                    var clone = source.cloneNode(true);
                    clone.setAttribute('name', name);
                    clone.setAttribute('sheetId', sheetId);
                    clone.setAttribute('r:id','rId3');
                    xlsx.xl['workbook.xml'].getElementsByTagName('sheets')[0].appendChild(clone);
    
                    //Add sheet2.xml to xl/worksheets
                    //===============================
                    var newSheet = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
                    '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac">'+
                    getTableData(table, title) +
    
                    '</worksheet>';
    
                    xlsx.xl.worksheets['sheet2.xml'] = $.parseXML(newSheet);
    
                }   
    
    
                var table_dias;
                table_dias = $('#listavendasdiadia').DataTable({ .............. })
    
  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0

    Any information that can help me in this question of printing 2 tables in a single button?

  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0

    Does anyone have any solution for this case !?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Sorry no - this is not currently possible in DataTables. We are looking at options to make it possible in future though.

    Allan

  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0

    Allan, good morning.
    I used the same function to create 1 single pdf with 2 datatables, and it worked. However, when canceling the print window, the TAB does not close.
    The function of generating 1 pdf with 2 datatables is above. Do you have any idea !?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    However, when canceling the print window, the TAB does not close.

    Check for errors in your browser's console.

    Kevin

  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0

    There is no mistake. No errors.
    But I will resolve and post here for you.

  • lauromnetolauromneto Posts: 129Questions: 0Answers: 0
    edited July 2020

    ------------- SOLVED -------------

    HTML:

    <iframe name="if1" id="if1" style="display:none"></iframe>

    JAVASCRIPT:

    {
        extend: 'print',
        text: 'Imprimir',
        title: 'Title',
        //download: 'open',
        action: function(e, dt, node, config){
    
            var config =    {
                className:"buttons-pdf buttons-html5",
                customize:null,
                download:"download",
                exportOptions:{},
                extension:".pdf",
                filename:"xxx",
                footer:true,
                header:true,
                messageBottom:"*",
                messagetop:"*",
                namespace:".dt-button-2",
                orientation:"portrait",
                pageSize:"A4",
                title:"*"
                };
    
            var tables = ["listavendasdiadia","listavendasdiadia1"];
            var tablesConverted = {};
            for(var k=0;k<tables.length;k++)
            {
                var dt = $('#'+tables[k]).DataTable();
                var data = dt.buttons.exportData( config.exportOptions );
                var info = dt.buttons.exportInfo( config );
    
                var rows = [];
    
                    if ( config.header ) {
                        rows.push( $.map( data.header, function ( d ) {
                            return {
                                text: typeof d === 'string' ? d : d+'',
                                style: 'tableHeader'
                            };
                        } ) );
                    }
    
                    for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
                        rows.push( $.map( data.body[i], function ( d ) {
                            return {
                                text: typeof d === 'string' ? d : d+'',
                                style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd'
                            };
                        } ) );
                    }
    
                    if ( config.footer && data.footer) {
                        rows.push( $.map( data.footer, function ( d ) {
                            return {
                                text: typeof d === 'string' ? d : d+'',
                                style: 'tableFooter'
                            };
                        } ) );
                    }
    
                    tablesConverted[tables[k]]=rows;
            }
    
    
                var doc = {
                    pageSize: config.pageSize,
                    pageOrientation: config.orientation,
                    content: [
                        "Data for "+tables[0],
                        {
                            table: {
                                headerRows: 1,
                                body: tablesConverted[tables[0]]
                            },
                            layout: 'noBorders'
                        },
                        " ",
                        "Data for "+tables[1],
                        " ",
                        {
                            table: {
                                headerRows: 1,
                                body: tablesConverted[tables[1]]
                            },
                            layout: 'noBorders'
                        },
    
                    ],
                    styles: {
                        tableHeader: {
                            bold: true,
                            fontSize: 11,
                            color: 'white',
                            fillColor: '#2d4154',
                            alignment: 'center'
                        },
                        tableBodyEven: {},
                        tableBodyOdd: {
                            fillColor: '#f3f3f3'
                        },
                        tableFooter: {
                            bold: true,
                            fontSize: 11,
                            color: 'white',
                            fillColor: '#2d4154'
                        },
                        title: {
                            alignment: 'center',
                            fontSize: 15
                        },
                        message: {}
                    },
                    defaultStyle: {
                        fontSize: 10
                    }
                };
    
                if ( info.messageTop ) {
                    doc.content.unshift( {
                        text: info.messageTop,
                        style: 'message',
                        margin: [ 0, 0, 0, 12 ]
                    } );
                }
    
                if ( info.messageBottom ) {
                    doc.content.push( {
                        text: info.messageBottom,
                        style: 'message',
                        margin: [ 0, 0, 0, 12 ]
                    } );
                }
    
                if ( info.title ) {
                    doc.content.unshift( {
                        text: info.title,
                        style: 'title',
                        margin: [ 0, 0, 0, 12 ]
                    } );
                }
    
                if ( config.customize ) {
                    config.customize( doc, config );
                }
                pdfMake.createPdf(doc).print({}, window.frames['if1']); 
                //pdfMake.createPdf(doc).print(); 
        }                   
    
    }
    
This discussion has been closed.