Tuesday, September 27, 2011

Print Button on SharePoint Page


We can easly add print functionality on SharePoint Page. Just add following Javascript on the page (you can use HTML Form Webpart for adding javascript).

In Javascript i have used WebPartElementID="onetIDListForm" ; which is SharePoint Default ID of the Main contents.

JavaScript:

<script type="text/javascript" language="JavaScript">
//Controls which Web Part or zone to print 'TD ID'
var WebPartElementID = "onetIDListForm"; //SharePoint Main Content ID

//Function to print Web Part
function PrintArea()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag

PrintingHTML += document.getElementsByTagName('head')[0].innerHTML;
PrintingHTML += '\n</HEAD>\n<BODY class="printSQS">\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML += WebPartData.innerHTML;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","PrintWebPart",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.close();
// Open Print Window
PrintingWindow.print();
}
}
</script>

HTML Code:

<input type="button" value="Print" onclick="javascript:void(PrintArea());return false;__doPostBack('btPrint','')" />

<a href="#" onclick="javascript:void(PrintArea());return false;__doPostBack('btPrint','')"  ><img src="/sites/aaa/PublishingImages/print.gif" border="0" complete="complete"/></a>


You can add html code any where on the page.

4 comments:

  1. Hi Amit, i used the above script and it works fine for me, the only concern is i get the standard font on the print window, i want the actual font wat is there on the page, can you help me here

    ReplyDelete
    Replies
    1. Nice Question. I have also faced the same issue but ignored.
      Let me explain you the logic of above print code.
      Above code select HTML from particular DIV and then create HTML Document and send it to print. Simple one.

      But it only take HTML Code not CSS Declaration. So that you have to take head tag for current doc and append it to New Doc in JavaScript code.

      Delete
  2. hi, how can I show "print preview window" instead of "print window"?

    ReplyDelete