Thursday, 29 November 2012

print content from sharepoint webpart


01<script type="text/javascript" src="http://www.google.com/jsapi"></script>
02<script type="text/javascript">
03  // Load jQuery
04  google.load("jquery", "1.2.6");
05</script>
06<script type="text/javascript">
07$(function(){
08    //find all web parts by their TD
09    var tags = $("td[id^='MSOZoneCell_WebPart']");
10    //loop through web parts
11    tags.each(function(){
12        //get id for print function
13        var tagid = $(this).attr("id");
14        //append an image with onClick event
15        $(this).find("h3 nobr").append(
16            "<span style='padding-left:20px;'>"+
17            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
18            "      <img src='/_layouts/images/nws16.gif' border='0' alt='printer friendly'/>"+
19            "  </a>"+
20            "</span>"
21        );
22    });
23});
24function printWebPart(tagid){
25    if (tagid) {
26        //build html for print page
27        var html = "<HTML>\n<HEAD>\n"+
28            $("head").html()+
29            "\n</HEAD>\n<BODY>\n"+
30            $("#"+tagid).html()+
31            "\n</BODY>\n</HTML>";
32        //open new window
33        var printWP = window.open("","printWebPart");
34        printWP.document.open();
35        //insert content
36        printWP.document.write(html);
37        printWP.document.close();
38        //open print dialog
39        printWP.print();
40    }
41}
42</script>
  Update 12/11/2008: Dave T requested a version of this script that works with the List View Web Part (no title displays). Great idea Dave! Replace the main function with this one, notice there is a second "append" process that looks for the toolbar space instead of the title area. 
01$(function(){
02    //find all web parts by their TD
03    var tags = $("td[id^='MSOZoneCell_WebPart']");
04    //loop through web parts
05    tags.each(function(){
06        //get id for print function
07        var tagid = $(this).attr("id");
08        //append an image with onClick event
09        $(this).find("h3 nobr").append(
10            "<span style='padding-left:20px;'>"+
11            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
12            "      <img src='/_layouts/images/nws16.gif' border='0' alt='printer friendly'/>"+
13            "  </a>"+
14            "</span>");
15        $(this).find("td.ms-toolbar[width='99%']").append(
16            "<span style='padding-left:20px;'>"+
17            "  <a href='#' onClick='printWebPart("+'"'+tagid+'"'+"); return false;'>"+
18            "      <img src='/_layouts/images/printerfriendly.gif' border='0' alt='printer friendly' />"+
19            "  </a>"+
20            "</span>");
21    });
22});