Articles in this section
Category / Section

How to print only selected records in grid

3 mins read

Problem discussion

Usually, Grid will print its content using the toolbar action or print method. This will print the whole data that has been bound to the Grid dataSource which is the default behavior. However, Grid provides an option to print only the selected records from the Grid. This can be done by binding the beforePrint event, where the whole rows of the Printing Grid can be replaced by the selected rows.

Initialize the Grid

Initialize the Grid with the Print tool and required number of columns. Bind the beforePrint event to the Grid.

import { createElement } from '@syncfusion/ej2-base';
import { Grid, Toolbar, PrintEventArgs, Print } from '@syncfusion/ej2-grids';
import { employeeData } from './data-source';
 
Grid.Inject(Toolbar, Print);
/**
 * Print Grid sample
 */
 
let grid: Grid = new Grid({
    dataSource: employeeData,
    allowSorting: true,
    toolbar: ['Print'],
    selectionSettings: { type: 'Multiple' },
    beforePrint: beforePrint,
    columns: [
        { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
        { field: 'FirstName', headerText: 'Name', width: 125 },
        { field: 'Title', headerText: 'Title', width: 180 },
        { field: 'City', headerText: 'City', width: 110 }
    ]
});
grid.appendTo('#Grid');

 

Define the event handler

Define the beforePrint event which handles the Grid’s Printing action with and without selected records. If the records were selected, it will print selected rows alone whereas the Grid without selected records, print the entire datasource.

 
let beforePrint = (e: PrintEventArgs) => {
    var rows = grid.getSelectedRows();
    if (rows.length) {
        e.element['ej2_instances'][0].getContent().querySelector('tbody').remove();
        var tbody = createElement('tbody');
        rows = [...rows];
        for (var r = 0; r < rows.length; r++) {
            tbody.appendChild(rows[r].cloneNode(true));
        }
        e.element['ej2_instances'][0].getContentTable().appendChild(tbody);
    }
}
 

 

 

Output:

 

Grid with the selected records

Figure 1: Grid with the selected records

Printing Window of Grid

Figure 2: Printed the selected records

 

TypeScript Demo: https://stackblitz.com/edit/print-types-fpe5p7?file=index.ts

Angular Demo: https://stackblitz.com/edit/print-selected-row?file=app.component.ts

React Demo: https://stackblitz.com/edit/print-rows-selected?file=index.js

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied