Print SharePoint Listview Web Part using JavaScript

Requirement is to Print a SharePoint List view web part with JavaScript.

Solution: Found this code somewhere on the Technet Forums: Place this code in a CEWP, This will add a “Print” button, on clicking the button, Script fetches the list view web part, place it in a new window and sends to Print.

<INPUT type="button" onclick="javascript:void(printwebpart('WebPartWPQ2'))" value="Print"/>

<script type="text/javascript">
function printwebpart(webpartid)
{
  var WebPartElementID = webpartid;
  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

  if (document.getElementsByTagName != null)
  {
  var HeadData= document.getElementsByTagName("HEAD");

  if (HeadData.length > 0)
  PrintingHTML += HeadData[0].innerHTML;
  }

  PrintingHTML += '\n</HEAD>\n<BODY>\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();
   PrintingWindow.focus();

   // Open Print Window
   PrintingWindow.print();
   PrintingWindow.close();
  }
}
</script>  

Output:

Print SharePoint Listview Web Part using JavaScript

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

2 thoughts on “Print SharePoint Listview Web Part using JavaScript

  • February 24, 2016 at 6:25 PM

    Thanks for the nice post.

    Mahmood Algoul – Comment the below line and see how it works in IE. I found that this one won’t work in Chrome.
    //PrintingWindow.close();

    Reply
  • August 31, 2015 at 5:50 AM

    Nice article, but for SPS 2013 it keep closing pop up window automatically.

    Reply

Leave a Reply