Preparing an asp.net master page for print only view – stripping out css etc

Searching google turned up nothing on this so did some digging in MSDN and worked out a method of disabling all the style sheets, javascript etc to produce a text only page:

1/ Add a content block to your master page – i’ve called mine ‘cssContentHolder’

<asp:contentplaceholder id=”cssContentHolder” runat=”server”>
<link rel=”stylesheet” href=”css/master.css” type=”text/css” media=”all” />
<link href=”css/flyout.css” media=”screen” rel=”stylesheet” type=”text/css” />
<script src=”scripts/APIs/JQuery/JQuery-1.3.2.min.js” type=”text/javascript”></script>
<script src=”scripts/APIs/JQuery/Plugins/jquery-ui-1.7.1.custom.min.js” type=”text/javascript”></script>
</asp:contentplaceholder>

2/ In the markup, add a link button so the user can click it to remove the formatting

<asp:LinkButton  PostBackUrl=”#” ID=”textLink”  runat=”server” Text=”Text Only Version” onclick=”textLink_Click” ></asp:LinkButton>

3/ In the code behind, create an event handler for the button and add the following code

protected void textLink_Click(object sender, EventArgs e)
{
bool Hidden = Page.Master.FindControl(“cssContentHolder”).Visible ;
Page.Master.FindControl(“cssContentHolder”).Visible = !Hidden;
if (Hidden)
textLink.Text = “Switch to Graphical Version”;
else
textLink.Text = “Text Only Version”;
}

That’s it. When you click on the link, you will perform a postback to the server, get the state of the control and show/hide accordingly. It will also change the text so you can click back again.

Simple when you know how!

Using Javascript, another method to remove all the CSS but not update any link text etc is to call the following function:

function hideCSS(){
	if(document.getElementsByTagName){
		for(n=0;n<document.getElementsByTagName("link").length;n++){
			if(document.getElementsByTagName("link")[n].getAttribute){
				if(document.getElementsByTagName("link")[n].getAttribute("rel").indexOf("stylesheet")!=-1){
					document.getElementsByTagName("link")[n].disabled="disabled"
					}
				}
			}
		}
	}