Printing from a Web programmer perspective is a quite tricky task. Because what we really able to control is on the server side, while the printing is done on the client side.
Unless you create some sort of cool Java applet or custom COM control to help you interface with the printer, you will stuck with Javascript’s Window.print() function.
For those who are stuck without the cool Java applet or the super cool COM control, hopefully this article will help you.
Let’s assume you have the following GridView in your aspx page:
<asp:gridview id="gvCustomersGridView" datasourceid="CustomersSource" autogeneratecolumns="true" emptydatatext="No data available." allowpaging="true" runat="server"> </asp>
To make this GridView printable, you need to share the clientID to your Javascript printing function. You could either do it by:
- previewing the page, copy the ID of the table generated and put it into a variable inside Javascript
- Or, you can create a protected variable and put the classic ASP <%= VarName %> inside Javascript
Next, we need to create the print button and the Javascript code to handle the printing.
function Print() { var grid_ID = 'gvCustomersGridView'; //assuming that this is the generated ID var grid_obj = document.getElementById(grid_ID); if (grid_obj != null) { var new_window = window.open('print.html'); //print.html is just a dummy page with no content in it. new_window.document.write(grid_obj.outerHTML); new_window.print(); new_window.close(); } }
You could also comment out the print() and close(), this way user will have a ‘print preview’ and has the chance to set margin, header/footer of the print out.
I hope you find it useful 🙂