Programatically forcing print styles to a web page in SharePoint

If you have a situation where you want to force print styling(or any other styling) on a page request made from any machine or application you have two options:

1. You identify the HTTP request header information(user agent) and see what application/source has requested this page request.

2. Specify a query string parameter that when encountered in a page request the wanted styling will be applied.

Basically both options have the same code which I will explain below. They only differ in the way the recognition of the printing request is done. In this example I will show the option number two.

A simple approach is to use a master page code or you could do it with a HttpHandler but a mater page approach is faster to do.

The code is rather simple:

  1. Identify the query string key and get the value
  2. Insert in the PlaceHolderAdditionalPageHead content placeholder control your CSS registration. This will add your CSS registration in the header of the HTML output. Notice that you gotta make sure your content placeholder is preferably just before the ending of the </head> HTML tag. This is to make sure that you CSS will overwrite anything else done before.

Here is the code:

String qsID = Request.QueryString[“myquerystingkey”];

            if (!String.IsNullOrEmpty(qsID))


                switch (qsID.ToLower())


                    case “print”:


                            if (this.PlaceHolderAdditionalPageHead != null)


                                this.PlaceHolderAdditionalPageHead.Controls.Add(new Literal() { Text = “<link rel=’stylesheet’ type=’text/css’ media=’all‘ href=’printer.css’>” });


                        } break;





Basically you can apply this to any form of web application just replace the page header control with some other method of inserting your CSS file reference. Also take notice that for this to work the media attribute on the link reference requires to be in the ALL mode not print. If it is set to print then you would have to make a print request to the browser. to do this you could do one of the following:

  1. Create a link button to perform the print: <A HREF=”javascript:window.print()”>Print me</A>
  2. Or you can do something similar what we did above with the CSS and insert a javascrip block with the invocation of the print request:

<script type=”text/javascript”>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s