Thursday, November 26, 2009

Create "printable" versions of the pages using ASP.NET MasterPages

Printing a page online usually means printing more than what you actually want. WebPages are quite fancy nowadays, with ad banners on top, navigational links on the left, and so on. By I wanted the printed pages to not include the menu bar and sidebars, only the content.

If you use master pages in the project, then one solution would be changing the current master page to another, which can be friendlier for printing. This can be done as follows.

Create a new master page, which may contain a border and a nice background. When is click on the link to the printer, then use the following JavaScript code:
function OpenPrintVersion() {
window.open(location.pathname + '?MasterPageEmpty=true');
return false;
}
This code will open the page in a new tab, adding a query string, who say that we must change the master page. Then on the page base from which all pages inherit from, we add:
protected void Page_PreInit(object sender, EventArgs e)
{
if (string.Compare(Request.QueryString["MasterPageEmpty"], "true") == 0)
{
MasterPageFile = "~/MasterPageEmpty.Master";
}
}
Now we have one more friendly printer page, but of course that all links in the page are active. To deactivate all links, buttons and imagebuttons in page, on MasterPageEmpty body onload call a JavaScript function “DeactivateAll”:

function DeactivateAll() {
for (i in document.links) {
document.links[i].onclick = function() { return false; };
}
var all = document.getElementsByTagName('input');
for (var i = 0; i < all.length; i++) {
if (all[i].getAttribute('type') == 'submit' ||
all[i].getAttribute('type') == 'image') {
all[i].onclick = function() { return false; };
}
}
}
Kind regards,
Dumitru

No comments: