Articles in this section
Category / Section

How to print the grid when barcode as one of the column in JS Grid?

1 min read

This knowledge base explains how to print the grid when Syncfusion canvas control such as barcode as one of the grid column using Print feature of JavaScript Grid.

Solution:

Using beforePrint event, we can print the grid with column contains syncfusion canvas control (ejBarcode) as one of the column by converting the canvas element into image. Initially we can display the ejBarcode in Grid by using column template feature of grid.

Render the Grid control.

HTML

 
<div id="Grid"></div>
 

 

JS

 
<script type="text/x-jsrender" id="columnTemplate">
       <div id="{{:EmployeeID}}barcode" class="barcode"></div>
 </script>
 
<script type="text/javascript">
    $(function () {
        $("#Grid").ejGrid({
                // the datasource "window.employeeView" is referred from jsondata.min.js
                dataSource: window.employeeView,
                allowPaging: true,
                pageSettings: {pageSize: 4},
                toolbarSettings: {showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.PrintGrid]},
                columns: [
                         {headerText: "Barcode", templateID: "#columnTemplate", textAlign: "center", width: 170},
                         {field: "EmployeeID", headerText: "Employee ID", textAlign: ej.TextAlign.Right, width: 90},
                         {field: "FirstName", headerText: "First Name", width: 90},
                         {field: "LastName", headerText: "Last Name", width: 90},
                         {field: "BirthDate", headerText: "Birth Date", width: 90, format: "{0:MM/dd/yyyy}"},
                         {field: "Country", headerText: "Country", width: 80}
                ],
                dataBound: "databound",
                templateRefresh: "refresh",
                beforePrint: "beforeprint"
        });
    }); 
 </script>

 

MVC

@(Html.EJ().Grid<object>("Grid")
         .Datasource((IEnumerable<object>)ViewBag.DataSource)
         .AllowPaging()  
         .PageSettings(p => { p.PageSize(4); })
         .ToolbarSettings(toolbar =>{
              toolbar.ShowToolbar().ToolbarItems(items =>
                {
                  items.AddTool(ToolBarItems.PrintGrid);
                });
         })
         .Columns(col =>{
               col.HeaderText("Barcode").Template("#columnTemplate")
.TextAlign(TextAlign.Center).Width(170).Add();
               col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(90).Add();
               col.Field("FirstName").HeaderText("First Name").Width(90).Add();
               col.Field("LastName").HeaderText("Last Name").Width(90).Add();
               col.Field("BirthDate").HeaderText("Birth Date”).Width(90).Format("{0:MM/dd/yyyy}").Add();
               col.Field("Country").HeaderText("Country”).Width(80).Add();
          })
            .ClientSideEvents(eve =>
                  {
                        eve.DataBound("databound");
                        eve.TemplateRefresh("refresh");
                        eve.BeforePrint("beforeprint");
                  })
 )
 

 

[Serverside code]
 
namespace EJGrid.Controllers
{
    public class HomeController: Controller
    {
        public ActionResult Index()
        {
            var DataSource = new NorthwindDataContext().EmployeeViews.ToList();
            ViewBag.DataSource = DataSource;
            return View();        
         }        
    }
}

 

ASP.NET

[aspx]
<ej:Grid ID="Grid" runat="server" AllowPaging="True"> 
  <ToolbarSettings ShowToolbar="True" ToolbarItems="printGrid">
   </ToolbarSettings>
   <PageSettings PageSize="4" />
   <ClientSideEvents DataBound="databound" TemplateRefresh="refresh" BeforePrint="beforeprint">
   </ClientSideEvents >
     <Columns>
          <ej:Column HeaderText="Barcode" Template="#columnTemplate" TextAlign="Center" Width="170" />
          <ej:Column Field="EmployeeID" HeaderText="Employee ID" TextAlign="Right" Width="90"/>
          <ej:Column Field="FirstName" HeaderText="First Name" Width="90"/>
          <ej:Column Field="LastName" HeaderText="Last Name" Width="90"/>                       
          <ej:Column Field="BirthDate" HeaderText="Birth Date" Format="{0:MM/dd/yyyy}" Width="90"/>
          <ej:Column Field="Country" HeaderText="Country" Width="80"/>                      
      </Columns>
</ej:Grid>  
 

 

 
[Serverside code]
 
public partial class _Default: Page
{    
    protected void Page_Load(object sender, EventArgs e)
    {
            this.Grid.DataSource = new NorthwindDataContext().EmployeeViews.ToList();
            this.Grid.DataBind();
    }
}

 

ASP.NET CORE

 

<ej-grid id="Grid" allow-paging="true" datasource="ViewBag.DataSource" databound="databound" template-refresh="refresh" before-print="beforeprint">
    <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> {"printGrid"}' />
    <e-page-settings page-size="4"></e-page-settings>
    <e-columns>
        <e-column header-text="Barcode" template="#columnTemplate" width="170"></e-column>
        <e-column field="EmployeeID" header-text="Employee ID" text-align="Right" width="80"></e-column>
        <e-column field="FirstName" header-text="First Name" width="90"></e-column>
        <e-column field="LastName" header-text="Last Name" width="90"></e-column>
        <e-column field="BirthDate" header-text="Birth Date" format="{0:MM/dd/yyyy}" width="90"></e-column>
        <e-column field="County" header-text="Country" width="80"></e-column>
    </e-columns>
</ej-grid>

 

[Serverside code]
 
public partial class GridController: Controller
    {
        public ActionResult GridFeatures()
        {
            var DataSource = new NorthwindDataContext().EmployeeViews.ToList();
            ViewBag.DataSource = DataSource;
            return View();
        }
    }

 

 

Angular

Define the template in the Index page.

 

<script type="text/x-jsrender" id="columnTemplate">
       <div id="{{:EmployeeID}}barcode" class="barcode"></div>
 </script>
 

 

HTML File

<ej-grid id="Grid" #grid [allowPaging]=true [dataSource]="gridData" (beforePrint)="onPrint($event)" (dataBound)="dataBound($event)" (templateRefresh)="refresh($event)" [pageSettings]="pageSettings"
 [toolbarSettings.showToolbar]="true" [toolbarSettings.toolbarItems]="tools" >
<e-columns>
                <e-column headerText="Barcode" template="#columnTemplate" textAlign="center" width="170"></e-column>
                <e-column field="EmployeeID" headerText="Employee ID" width="90"></e-column>
                <e-column field="FirstName" headerText="First Name" width="90"></e-column>
                <e-column field="LastName" headerText="Last Name" width="90"></e-column>
                <e-column field="BirthDate" headerText="Birth Date" format="{0:MM/dd/yyyy}" width="90"></e-column>
                <e-column field="Country" headerText="Country" width="80"></e-column>
     </e-columns>        
</ej-grid>

 

 

Ts File

export class AppComponent {
    public gridData;
    public tools;
    public pageSettings;
    @ViewChild('grid') Grid: EJComponents<any, any>;
    constructor() {
//The datasource "window.employeeView" is referred from 'http://js.syncfusion.com/demos/web/scripts/jsondata.min.js'
            this.gridData = window.employeeView;
            this.pageSettings = { pageSize: 4 };
            this.tools = ["printGrid"];
    }
// convert the element to corresponding controls by using templateRefresh and databound event of grid.    
    refresh(e:any){      
        var grid = $("#Grid").ejGrid("instance");
        if(!grid.initialRender){
            var text = e.data.EmployeeID;
            var val = text.toString();
            $(e.cell).find(".barcode").ejBarcode({ text: val, symbologyType: "qrbarcode" });
        }       
    }
    dataBound(e){
        var data = e.model.currentViewData;
            for (var j = 0; j < data.length; j++) {
                var text = data[j].EmployeeID;
                $(".barcode").eq(j).ejBarcode({ text: text.toString(), symbologyType: "qrbarcode" });
            }
    }
// convert this canvas element to image and then print the ejBarcode control.
    onPrint(e) {
            if (e.requestType == "print") {
                var img = new Image();
                var len = e.element.find(".barcode").length;
                e.model.allowPaging = false;
                  var grid = $("#" + this.Grid.widget._id).ejGrid("instance"); 
                grid.refreshContent();
                grid.getPager().css('display', 'none');
                for (var i = 0; i < len; i++) {
                    img = new Image();
                    img.src = $(".barcode").children("canvas")[i].toDataURL();
                    e.element.find(".barcode").eq(i).parent("td").append(img);
                }
                grid.model.allowPaging = true;
                grid.refreshContent();
                grid.getPager().css('display', 'block');
            }
        } 
}

 

Using template property of grid columns, we can add ejBarcode control as one of the grid column. Create an element using jsRender and convert the element to corresponding control by using templateRefresh and dataBound event of the grid.

 

<script type="text/javascript">
function refresh(args) {
                if (!this.initialRender) {
                var text = args.data.EmployeeID;
                $(args.cell).find(".barcode").ejBarcode({ text: text.toString(), symbologyType: "qrbarcode" });
            }
}
function databound(args) {
             var data = this.model.currentViewData;
            for (var j = 0; j < data.length; j++) {
                var text = data[j].EmployeeID;
                this.element.find(".barcode").eq(j).ejBarcode({ text: text.toString(), symbologyType: "qrbarcode" });
            }
 }
</script>

In beforePrint event, convert the canvas element to image and then print the ejBarcode control.

 

<script type="text/javascript">  
function beforeprint (args) {
             if (args.requestType == "print") {
                var img = new Image();
                var len = args.element.find(".barcode").length;
                this.model.allowPaging = false;
                var grid = $("#" + this._id).ejGrid("instance"); 
                grid.refreshContent();
                grid.getPager().css('display', 'none');
                for (var i = 0; i < len; i++) {
                    img = new Image();
                    img.src = $(".barcode").children("canvas")[i].toDataURL();
                    args.element.find(".barcode").eq(i).parent("td").append(img);
                }
                grid.model.allowPaging = true;
                grid.refreshContent();
                grid.getPager().css('display', 'block');
                    }
                 }
</script>

 

Figure 1 Grid with barcode control

 

 

Print barcode control

Figure 2 To print barcode control

 

Conclusion

I hope you enjoyed learning about how to print the grid when barcode as one of the column in JS Grid.

You can refer to our JavaScript Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.  You can also explore our JavaScript Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

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