Print in ASP.NET MVC Grid component

21 Oct 202420 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.

@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("130").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 = OrdersDetails.GetAllRecords();
    return View();
}

Print

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:

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">
  @Html.EJS().Button("printbtn").Content("Print").IsPrimary(true).Render()
</div>
@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 = OrdersDetails.GetAllRecords();
    return View();
}

Print by external button

By default, the Syncfusion ASP.NET MVC 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">
    @Html.EJS().DropDownList("dropdown").Index(0).DataSource(@ViewBag.dropdownData).Change("change").Render()
  </span>
</div>

@Html.EJS().Grid("Grid").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 ID").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().PageSettings(page => { page.PageSize(6); }).Toolbar(new List<string>() { "Print" }).Render()

<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 visible Page

By default, the Syncfusion ASP.NET MVC 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 MVC 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 MVC Grid:

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).BeforePrint("beforePrint").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
   col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();

}).AllowPaging().SelectionSettings(select => select.Type(Syncfusion.EJ2.Grids.SelectionType.Multiple)).PageSettings(page => page.PageSize(6)).Toolbar(new List<string>() { "Print" }).Render()
<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 only selected records

The Syncfusion ASP.NET MVC 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 MVC 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="Ship Country", Width="90" },
        new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipAddress", HeaderText="ShipAddress", 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">
    @Html.EJS().DropDownList("dropdown").Index(0).DataSource(@ViewBag.dropdownData).Change("onModeChange").Render()
  </span>
</div>
 @Html.EJS().Grid("HierarchyPrint").DataSource((IEnumerable<object>)ViewBag.EmpDataSource).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();

 }).Toolbar(new List<string>() { "Print" }).ChildGrid(ChildGrid).Render()
 <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 hierarchy grid

The Syncfusion ASP.NET MVC 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 BeforePrintevent in the ASP.NET MVC 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.

<div>
    <B>Master Grid</B>
    @Html.EJS().Grid("masterGrid").DataSource((IEnumerable<object>)ViewBag.EmployeeData).SelectedRowIndex(1).Columns(col =>
{
   col.Field("ContactName").HeaderText("Customer Name").Width(150).Add();
   col.Field("CompanyName").HeaderText("CompanyName").Width(150).Add();
   col.Field("Address").HeaderText("Address").Width(150).Add();
   col.Field("Country").HeaderText("Country").Width(130).Add();

}).RowSelected("rowSelected").BeforePrint("beforePrint").Toolbar(new List<string>() { "Print" }).Render()
</div>
<p><div style="padding: 8px 0px 10px 0px;" class='e-statustext'> Showing orders of Customer:  <b id=key></b></div></p>
<div>
@Html.EJS().Grid("childGrid").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("120").Add();
   col.Field("ShipAddress").HeaderText("Ship Address").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();


}).Render()
</div>
<script>
function rowSelected(args) {
    let 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));
    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 the master detail grid

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.

Scale Option Setting

Show or hide columns while printing

In the Syncfusion ASP.NET MVC 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:

@Html.EJS().Grid("Grid").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 ID").Visible(false).Width("150").Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();

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

<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(); 
}

Show or hide columns while printing

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 MVC 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.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).BeforePrint("beforePrint").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
   col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();

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

<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();
}

Retain grid styles while printing

To print the Syncfusion ASP.NET MVC 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">
    @Html.EJS().Button("print").CssClass("e-danger").Content("Print").Render()
</div>
@Html.EJS().Grid("HierarchyPrint").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
  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();

}).AllowPaging().PageSettings(page => { page.PageSize(10); }).PrintMode(Syncfusion.EJ2.Grids.PrintMode.CurrentPage).ActionComplete("actionComplete").DataBound("dataBound").BeforePrint("beforePrint").Render()

@Html.EJS().Chart("chart").Series(series =>
{
    series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(1).XName("OrderDate")
    .YName("Freight").ColumnWidth(0.4).Marker(mr => mr.Visible(true)).Add();

}).PrimaryXAxis(px =>px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.LabelFormat("MMMd")).PrimaryYAxis(py =>py.LabelFormat("{value}")).Title("Order Data").Render()
<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();
}

Print grid along with other components