Add a printer friendly button to SharePoint publishing page

One of the request from my client is to allow user to print a page with only text content on it. This feature is quite common in many websites.

After reading Kathy Hughes “Microsoft SharePoint Designer 2010 Unleashed”, it’s pretty easy to do so in SharePoint 2010.

Scenario: I have 3 custom page layout for my site, home page layout, landing page layout and detail page layout. I only want to have a print button on pages that uses content page layout.

Here are the steps:

1. Create a new CSS file in the site collection’s Style Library and name it print.css. In this file, you can try hide all the components that you don’t want to see in the print view.

2. Open detail page layout. Add the following html inside the PlaceHolderMain tag.

< a id=”printer” onclick=”myPrinter(‘printer’)” href=”#” target=”_blank”><img src=”/Style Library/images/printer.png”></a>

3. On the same page, scroll to the top. Find the closing tag of PlaceHolderAdditionalPageHead. If you don’t have this tag, you need to add it first. Add the following JavaScript immediate before the closing tag. Of course you can add these code to a js file and add the link here instead.

<script type=”text/javascript”>
//if the url doesn’t contain printfriendly, use the normal style sheet
if (location.search.indexOf(‘printfriendly’) == -1){
document.write(‘<link rel=”stylesheet” type=”text/css” href=”/Style Library/css/gw_content_style.css”/>’);
}
//otherwise use the print style sheet and open the print window
else
{
document.write(‘<link rel=”stylesheet” type=”text/css” href=”/Style Library/css/gw_print.css”/>’);
window.print();
}

function myPrinter(id)
{
//if url doesn’t contain a question mark
if(location.search.indexOf(‘?’) ==-1)
{
var qrystr = document.getElementById(id).href;
//if  the url doesn’t contain a hash
if (qrystr.indexOf(‘#’) == -1)
{
//use the existing url.
//This means the button has been pressed before
//so the printfriendly parameter is already added.
document.getElementById(id).href = qrystr;
}
//otherwise the button hasn’t been pressed before
//so remove the # and add the printfriendly parameter
else
{
var newstr = qrystr.replace(‘#’, ‘?printfriendly=true’);
document.getElementById(id).href = newstr;
}
}
//this is used for pages like DisplayFullStory?ID=3 which has a parameter
else
{
var qrystr = document.getElementById(id).href;
if (qrystr.indexOf(‘#’) == -1)
{
document.getElementById(id).href = qrystr;
}
else
{
var newstr = qrystr.replace(‘#’, ‘&printfriendly=true’);
document.getElementById(id).href = newstr;
}
}
}
</script>

4. That’s it. When you test it, make sure you go to a page that uses the detail page layout.

 

Reference:

http://www.codingforums.com/archive/index.php/t-80517.html

Advertisements