Print in ASP.NET Core Grid component
21 Oct 202424 minutes to read
The printing feature in Syncfusion Grid allows you to easily generate and print a representation of the grid’s content for better offline accessibility and documentation. You can enable this feature using either the grid’s toolbar or the programmatically available print
method.
To add the printing option to the grid’s toolbar, simply include the toolbar property in your grid configuration and add the Print as toolbar item. This will allow you to directly initiate the printing process while click on the Print item from the toolbar.
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowPaging='true' toolbar="@(new List<string>() { "Print" })" >
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
<e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format='C' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}
Page setup
When printing a webpage, some print options, such as layout, paper size, and margin settings, cannot be configured through JavaScript code. Instead, you need to customize these settings using the browser’s page setup dialog. Below are links to the page setup guides for popular web browsers:
Print by external button
You can print the grid’s content using an external button by utilizing the print
method. This method allows you to trigger the printing process programmatically.
<div style="padding-bottom:20px">
<ejs-button id="printbtn" content="Print" isPrimary="true"></ejs-button>
</div>
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource">
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
<e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format='C' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
document.getElementById('printbtn').onclick = function () {
document.getElementById('Grid').ej2_instances[0].print();
}
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}
Print visible Page
By default, the Syncfusion ASP.NET Core Grid prints all the pages of the grid. The printMode property within the grid grants you control over the printing process. However, if you want to print only the current visible page, you can achieve this by setting the printMode
property to CurrentPage.
<div style="display: flex">
<label style="padding: 3px 10px 26px 0;font-weight:bold"> Sekect print mode: </label>
<span style="height:fit-content">
<ejs-dropdownlist id="dropdown" index="0" dataSource="@ViewBag.dropdownData" change="change"></ejs-dropdownlist>
</span>
</div>
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowPaging='true' toolbar="@(new List<string>() { "Print" })">
<e-grid-pagesettings pageSize="6">
</e-grid-pagesettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
<e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format='C' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function change(args)
{
document.getElementById('Grid').ej2_instances[0].printMode = args.value;
}
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
ViewBag.dropdownData = new string[] { "AllPages", "CurrentPage" };
return View();
}
Print only selected records
By default, the Syncfusion ASP.NET Core Grid prints all the data bound to its dataSource. However, there might be cases where you want to print only the selected records from the grid. The ASP.NET Core Grid provides an option to achieve this by binding to the beforePrint event, where you can replace the rows of the printing grid with the selected rows.
Below is an example code that demonstrates how to print only the selected records from the ASP.NET Core Grid:
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowPaging='true'
beforePrint="beforePrint" toolbar="@(new List<string>() { "Print" })">
<e-grid-selectionsettings type="Multiple"></e-grid-selectionsettings>
<e-grid-pagesettings pageSize="6"></e-grid-pagesettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function beforePrint(args) {
var rows = document.getElementById('Grid').ej2_instances[0].getSelectedRows();
if (rows.length) {
args.element["ej2_instances"][0].getContent().querySelector("tbody").remove();
var tbody = document.createElement("tbody");
rows = [...rows];
for (var r = 0; r < rows.length; r++) {
tbody.appendChild(rows[r].cloneNode(true));
}
args.element["ej2_instances"][0].getContentTable().appendChild(tbody);
}
};
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}
Print the hierarchy grid
The Syncfusion ASP.NET Core Grid allows you to print hierarchy grids, which consist of a parent grid and its child grids. By default, when you print a hierarchy grid, it includes the parent grid and expanded child grids only. However, you can customize the print behavior using the hierarchyPrintMode property.
The hierarchyPrintMode
property in the ASP.NET Core Grid lets you control the printing behavior for hierarchy grids. You can choose from three options:
Mode | Behavior |
---|---|
Expanded | Prints the parent grid with expanded child grids. |
All | Prints the parent grid with all the child grids, whether expanded or collapsed. |
None | Prints the parent grid alone. |
@{
var SecondChildGrid = new Syncfusion.EJ2.Grids.Grid()
{
DataSource = (IEnumerable<object>)ViewBag.CustomerDataSource,
QueryString = "CustomerID",
Columns = new List<Syncfusion.EJ2.Grids.GridColumn> {
new Syncfusion.EJ2.Grids.GridColumn(){ Field="CustomerID", HeaderText="Customer ID", Width="90", TextAlign=Syncfusion.EJ2.Grids.TextAlign.Right },
new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipCountry", HeaderText="Country", Width="90" },
new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipAddress", HeaderText="Ship Address", Width="90" },
}
};
}
@{
var ChildGrid = new Syncfusion.EJ2.Grids.Grid()
{
DataSource = (IEnumerable<object>)ViewBag.DataSource,
QueryString = "EmployeeID",
Columns = new List<Syncfusion.EJ2.Grids.GridColumn> {
new Syncfusion.EJ2.Grids.GridColumn(){ Field="OrderID", HeaderText="Order ID", Width="120" },
new Syncfusion.EJ2.Grids.GridColumn(){ Field="Freight", HeaderText="Freight", Width="120", Format="C2", TextAlign=Syncfusion.EJ2.Grids.TextAlign.Right },
new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipName", HeaderText="Ship Name", Width="150" },
new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipCity", HeaderText="Ship City", Width="120" },
},
ChildGrid = SecondChildGrid
};
}
<div style="display: flex">
<label style="padding: 3px 10px 26px 0;font-weight:bold"> Select Mode: </label>
<span style="height:fit-content">
<ejs-dropdownlist id="dropdown" index="0" dataSource="@ViewBag.dropdownData" change="onModeChange"></ejs-dropdownlist>
</span>
</div>
<ejs-grid id="HierarchyPrint" dataSource="@ViewBag.EmpDataSource" childGrid="ChildGrid" toolbar="@(new List<string>() {"Print" })">
<e-grid-columns>
<e-grid-column field="EmployeeID" headerText="Employee ID" textAlign="Right" width="125"></e-grid-column>
<e-grid-column field="FirstName" headerText="Name" width="120"></e-grid-column>
<e-grid-column field="LastName" headerText="Last Name" width="170"></e-grid-column>
<e-grid-column field="City" headerText="City" textAlign="Right" width="135"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function onModeChange(args) {
document.getElementById('HierarchyPrint').ej2_instances[0].hierarchyPrintMode = args.value;
};
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();;
ViewBag.EmpDataSource = EmployeeView.GetAllRecords();
ViewBag.CustomerDataSource = Customer.GetAllRecords();
ViewBag.dropdownData = new string[] { "Expanded", "All", "None" };
return View();
}
Print the master detail grid
The Syncfusion ASP.NET Core Grid provides the option to visualize details of a record in another grid in a master-detail manner. By default, when you print a master-detail grid, only the master grid is included in the print output. However, you can customize the print behavior to include both the master and detail grids using the beforePrint
event of the grid.
The beforePrint event in the ASP.NET Core Grid is triggered before the actual printing process begins. You can handle this event to customize the print output. By adding the detail grid to the element
argument of the beforePrint
event, you can ensure that both the master and detail grids are printed on the page.
@using System.Text.Json;
<div>
<ejs-grid id="masterGrid" dataSource="@ViewBag.employeeDataSource" selectedRowIndex="1" toolbar="@(new List<string>() { "Print" })" rowSelected="rowSelected" beforePrint="beforePrint">
<e-grid-columns>
<e-grid-column field="ContactName" headerText="Contact Name" width="150"></e-grid-column>
<e-grid-column field="CompanyName" headerText="Company Name" width="150"></e-grid-column>
<e-grid-column field="Address" headerText="Address" width="150"></e-grid-column>
<e-grid-column field="Country" headerText="Country" width="130"></e-grid-column>
</e-grid-columns>
</ejs-grid>
</div>
<p><div style="padding: 8px 0px 10px 0px;" class='e-statustext'> Showing orders of Customer: <b id=key></b></div></p>
<ejs-grid id="childGrid">
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format='C' textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
<e-grid-column field="ShipAddress" headerText="ShipAddress" width="150"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function rowSelected(args) {
let selectedRecord = args.data;
var data = @Html.Raw(JsonSerializer.Serialize(ViewBag.DataSource));
var employeeID = args.data.EmployeeID;
var detaildata = new ej.data.DataManager(data).executeLocal(new ej.data.Query().where("EmployeeID", "equal", employeeID, false));
var grid = document.getElementById("childGrid").ej2_instances[0];
grid.dataSource = new ej.data.DataManager(detaildata).dataSource.json;
document.getElementById("key").innerHTML = selectedRecord.ContactName;
};
function beforePrint(args) {
var customEle = document.createElement('div');
var grid = document.getElementById("childGrid").ej2_instances[0];
customEle.innerHTML = document.getElementsByClassName('e-statustext')[0].innerHTML + grid.element.innerHTML;
customEle.appendChild(document.createElement('br'));
args.element.append(customEle);
};
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
ViewBag.EmployeeData =Employees.GetAllRecords();
return View();
}
Print large number of columns
When printing a grid with a large number of columns, the browser’s default page size (usually A4) might not be sufficient to display all the columns properly. As a result, the browser’s print preview may automatically hide the overflowed content, leading to a cut-off appearance.
To show a large number of columns when printing, you can adjust the scale option from the print option panel based on your content size. This will allow you to fit the entire grid content within the printable area.
Show or hide columns while printing
In the Syncfusion ASP.NET Core Grid, you have the flexibility to control the visibility of columns during the printing process. You can dynamically show or hide specific columns using the toolbarClick and printComplete events while printing. This capability enhances your control over which columns are included in the printed output, allowing you to tailor the printed grid to your specific needs.
In the toolbarClick
event, you can show or hide columns by setting column.visible
property to true or false respectively.
In the printComplete
event, the column visibility state is reset back to its original configuration.
Here’s a code example that demonstrates how to show a hidden column (CustomerID) and hide a visible column (ShipCity) during printing and then reset their visibility after printing:
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" toolbar="@(new List<string>() { "Print" })" toolbarClick='toolbarClick' printComplete='printComplete'>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" visible="false" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function toolbarClick() {
const columns = document.getElementById('Grid').ej2_instances[0].columns;
for (const column of (columns)) {
if (column.field == "CustomerID") {
column.visible = true;
} else if (column.field == "ShipCity") {
column.visible = false;
}
}
};
function printComplete () {
const columns = document.getElementById('Grid').ej2_instances[0].columns;
for (const column of (columns)) {
if (column.field == "CustomerID") {
column.visible = false;
} else if (column.field == "ShipCity") {
column.visible = true;
}
}
};
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}
Limitations of printing large data
Printing a large volume of data all at once in the grid can have certain limitations due to potential browser performance issues. Rendering numerous DOM elements on a single page can lead to browser slowdowns or even hang the browser. The grid offers a solution to manage extensive datasets through virtualization. However, it’s important to note that virtualization for both rows and columns is not feasible during the printing process.
If printing all the data remains a requirement, an alternative approach is recommended. Exporting the grid data to formats like Excel or CSV or Pdf is advised. This exported data can then be printed using non-web-based applications, mitigating the potential performance challenges associated with printing large datasets directly from the browser.
Retain grid styles while printing
The Syncfusion ASP.NET Core Grid provides a beforePrint event that allows you to customize the appearance and styles of the grid before it is sent to the printer. By handling this event, you can ensure that the grid retains its styles and appearance while printing.
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" beforePrint="beforePrint" toolbar="@(new List<string>() { "Print" })">
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<style>
.e-grid .e-headercell {
background: #24a0ed !important;
}
.e-grid .e-row .e-rowcell {
background: #cbecff !important;
}
.e-grid .e-altrow .e-rowcell {
background: #e7d7f7 !important;
}
</style>
<script>
function beforePrint() {
const styleElement = document.createElement('style');
styleElement.innerHTML = `
.e-grid .e-headercell {
background: #24a0ed !important;
}
.e-grid .e-row .e-rowcell {
background: #cbecff !important;
}
.e-grid .e-altrow .e-rowcell {
background: #e7d7f7 !important;
}
`;
document.head.appendChild(styleElement);
};
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}
Print grid along with other components
To print the Syncfusion ASP.NET Core Grid along with another component, such as a chart, you can use the beforePrint event of the grid. In this event, you can clone the content of the other component and append it to the print document.
Here is an example of how to print grid along with chart component:
<div style="padding-bottom:20px">
<ejs-button id="print" cssClass="e-danger" content="Print"></ejs-button>
</div>
<!-- Grid Component -->
<ejs-grid id="HierarchyPrint" dataSource="@ViewBag.DataSource" allowPaging="true" printMode="CurrentPage"
dataBound="dataBound" actionComplete="actionComplete" beforePrint="beforePrint">
<e-grid-pagesettings pageSize="10"></e-grid-pagesettings>
<e-grid-columns>
<e-grid-column field="OrderDate" headerText="Order Date" width="130" format="yMd" textAlign="Right"></e-grid-column>
<e-grid-column field="Freight" width="120" format="C2" textAlign="Right"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<!-- Chart Component -->
<h4>Chart</h4>
<div>
<ejs-chart id="chart" title="Order Data" width="60%">
<e-chart-primaryxaxis valueType="DateTime" labelFormat="MMMd"></e-chart-primaryxaxis>
<e-chart-primaryyaxis labelFormat='{value}'></e-chart-primaryyaxis>
<e-series-collection>
<e-series type="@Syncfusion.EJ2.Charts.ChartSeriesType.Line" xName="OrderDate" yName="Freight" width="1" columnWidth="0.4">
<e-series-marker visible="true"></e-series-marker>
</e-series>
</e-series-collection>
</ejs-chart>
</div>
<script>
function dataBound() {
var chart = document.getElementById('chart').ej2_instances[0];
chart.series[0].marker = { visible: true };
chart.series[0].xName = 'OrderDate';
chart.series[0].yName = 'Freight';
chart.series[0].dataSource = document.getElementById('HierarchyPrint').ej2_instances[0].getCurrentViewRecords();
}
document.getElementById('print').onclick = function () {
var grid = document.getElementById('HierarchyPrint').ej2_instances[0];
grid.print();
}
function beforePrint(args) {
var chartContainer = document.getElementById('chart').ej2_instances[0].element;
var clonedChartContainer = chartContainer.cloneNode(true);
args.element.appendChild(clonedChartContainer);
}
function actionComplete(args) {
if (args.requestType === 'paging') {
var chart = document.getElementById('chart').ej2_instances[0];
chart.series[0].dataSource = document.getElementById('HierarchyPrint').ej2_instances[0].getCurrentViewRecords();
chart.refresh();
}
}
</script>
public IActionResult Index()
{
ViewBag.DataSource = OrdersDetails.GetAllRecords();
return View();
}