SharePoint 2013/2010 – Printing Web Part with Styles using JavaScript

Welcome to my blog.  This is my first blog.

Today I came across one situation where I need to print the Web Part content using JavaScript.  But the main challenge is to retain the styles as it is.

If any one come the same situation, here the code to resolve your problem.  You can add this code using Content Editor web part or Script Editor web part (SP 2013).

<script src=//code.jquery.com/jquery-1.10.2.js”></script>
<script>
$(document).ready(function()
{
//replace your ID with web part id or inside table id of web part
var printContent = document.getElementById(layoutsTable).innerHTML;
 
//Header section to include CSS and JavaScript references
var printHeadContent =<HTML><HEAD>\n+
document.getElementsByTagName(HEAD)[0].innerHTML +‘</HEAD>\n<BODY>\n’;
 
$(#layoutsTable.div).each(function( index )
{
this.innerHTML.replace(inlineblock,block);
});
 
//Complete web part content
printContent = printHeadContent + document.getElementById(layoutsTable).innerHTML +
\n</BODY></HTML>‘;
var windowUrl = ‘about:blank’;
var uniqueName = new Date();
var windowName =Print+ uniqueName.getTime();
 
var printWindow = window.open(windowUrl, windowName,left=50000,top=50000,width=0,height=0);
printWindow.document.open();
printWindow.document.write(printContent);
printWindow.document.close();
printWindow.focus();
 
//Delay 5 seconds so that All JavaScript and CSS files loaded before printing
setTimeout(function()
{
printWindow.print();
printWindow.close();
},5000);
});
</script>

 

 

This entry was posted in SharePoint 2013. Bookmark the permalink.

Leave a Reply