Print in ASP.NET MVC Grid Component

7 Jan 202312 minutes to read

To print the Grid, use the print method from grid instance. The print option can be displayed on the Toolbar by adding the Print toolbar item.

@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().Toolbar(new List<string>() { "Print" }).Render()
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

Page setup

Some of the print options cannot be configured through JavaScript code. So, you have to customize the layout, paper size, and margin options using the browser page setup dialog. Refer to the following links to know more about the browser page setup:

To print the grid from an external button, invoke the print method.

@Html.EJS().Button("printbtn").Content("Print").IsPrimary(true).Render()

@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
  col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
  col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
  col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().Render()

<script>

  document.getElementById('printbtn').onclick = function () {
    document.getElementById('Print').ej2_instances[0].print();
  }

</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

By default, the grid prints all the pages. To print the current page alone, set the PrintMode to CurrentPage.

@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
  col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
  col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
  col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().Toolbar(new List<string>() { "Print" }).PrintMode(Syncfusion.EJ2.Grids.PrintMode.CurrentPage).Render()
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

By default, the grid will be print the master and expanded child grids alone. you can change the print option by using the hierarchyPrintMode property. The available options are,

Mode Behavior
Expanded Prints the master grid with expanded child grids.
All Prints the master grid with all the child grids.
None Prints the master 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="Ship Country", 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
    };
}

@Html.EJS().Grid("HierarchyPrint").DataSource((IEnumerable<object>)ViewBag.EmpDataSource).HierarchyPrintMode(Syncfusion.EJ2.Grids.HierarchyGridPrintMode.All).Columns(col =>
{
   col.Field("EmployeeID").HeaderText("Employee ID").Width("125").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("FirstName").HeaderText("Name").Width("125").Add();
   col.Field("Country").HeaderText("Country").Width("180").Add();
   col.Field("City").HeaderText("City").Width("135").Add();

}).AllowSorting().Toolbar(new List<string>() { "Print"}).ChildGrid(ChildGrid).Render()
public IActionResult Index()
{
    ViewBag.DataSource =  OrdersDetails.GetAllRecords();;
    ViewBag.EmpDataSource = EmployeeView.GetAllRecords();
    ViewBag.CustomerDataSource = Customer.GetAllRecords();
    return View();
}
public IActionResult Index()
{
    ViewBag.DataSource =  OrdersDetails.GetAllRecords();;
    ViewBag.EmpDataSource = EmployeeView.GetAllRecords();
    ViewBag.CustomerDataSource = Customer.GetAllRecords();
    return View();
}

NOTE

By default, the hierarchy grid prints the expanded child grids from the visible page only. Refer To Print the expanded state grid from all pages.

The Grid has the option to visualize details of a record in another Grid in a master and detailed manner. By default, Grid will print the master grid alone. Instead of this, it is possible to print both the master and detail grids by using the BeforePrint event of the Grid.

In the following sample, the detail grid is added to the element argument of the BeforePrint event, resulting in both the master and detail grids being printed on the page.

<div>
    <B>Master Grid</B>
    @Html.EJS().Grid("masterGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).Width("auto").SelectedRowIndex(0).Columns(col =>
        {
            col.Field("EmployeeID").HeaderText("EmployeeID").IsPrimaryKey(true).Add();
            col.Field("OrderID").HeaderText("OrderID").Add();
            col.Field("CustomerID").HeaderText("FirstName").Add();
        }).RowSelected("selected").BeforePrint("beforePrint").Toolbar(new List<string>() { "Print" }).Render()
</div>
<p><div class='e-statustext'> Showing orders of Customer:  <b id=key></b></div></p>
<div>
    @Html.EJS().Grid("detailGrid").DataSource((IEnumerable<object>)ViewBag.dataSource1).Columns(col =>
                {
                    col.Field("EmployeeID").HeaderText("EmployeeID").IsPrimaryKey(true).Add();
                    col.Field("ShipCountry").HeaderText("ShipCountry").Add();
                    col.Field("ShipName").HeaderText("ShipName").Add();
                }).Render()
</div>
<script>
    function selected(args) {
        var selectedRecord = args.data;
        var data = @Html.Raw(Json.Encode(ViewBag.datasource));
        var employeeID = args.data.EmployeeID;
        var detaildata = new ej.data.DataManager(data).executeLocal(new ej.data.Query().where("EmployeeID", "equal", employeeID, false).take(10));
        var grid = document.getElementById("detailGrid").ej2_instances[0];
        document.getElementById('key').innerHTML = selectedRecord.EmployeeID;
        grid.dataSource = new ej.data.DataManager(detaildata.slice(0, 5)).dataSource.json;
    }
    function beforePrint(args) {
        var customEle = document.createElement('div');
        var grid = document.getElementById("detailGrid").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 = OrderDetails.GetAllRecords();
    return View();
}

By default, the browser uses A4 as page size option to print pages and to adapt the size of the page the browser print preview will auto-hide the overflowed contents. Hence grid with large number of columns will cut off to adapt the print page.

To show large number of columns when printing, adjust the scale option from print option panel based on your content size.

Scale Option Setting

Show or Hide columns while Printing

You can show a hidden column or hide a visible column while printing the grid using ToolbarClick and PrintComplete events.

In the ToolbarClick event, based on args.item.id as grid_print. We can show or hide columns by setting Visible property of Column to true or false respectively.

In the PrintComplete event, We have reversed the state back to the previous state.

In the below example, we have CustomerID as a hidden column in the grid. While printing, we have changed CustomerID to visible column and ShipCity as hidden column.

@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.DataSource).ToolbarClick("toolbarClick").PrintComplete("printComplete").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Visible(false).Width("150").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();

}).AllowPaging().Toolbar(new List<string>() { "Print" }).Render()

<script>
    function toolbarClick(args) {
        for (var i = 0; i < this.columns.length; i++) {
            if (this.columns[i].field == "CustomerID") {
                this.columns[i].visible = true;
            }
            else if (this.columns[i].field == "ShipCity") {
                this.columns[i].visible = false;
            }
        }
    }

    function printComplete(args) {
        for (var i = 0; i < this.columns.length; i++) {
            if (this.columns[i].field == "CustomerID") {
                this.columns[i].visible = false;
            }
            else if (this.columns[i].field == "ShipCity") {
                this.columns[i].visible = true;
            }
        }
    }
</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}

Limitations of Printing Large Data

When grid contains large number of data, printing all the data at once is not a best option for the browser performance. Because to render all the DOM elements in one page will produce performance issues in the browser. It leads to browser slow down or browser hang. Grid have option to handle large number of data by Virtualization. However while printing, it is not possible to use virtualization for rows and columns.

If printing of all the data is still needed, we suggest to Export the grid to Excel or CSV or Pdf and then print it from another non-web based application.

See Also