Pages

Monday, December 19, 2016

Print SharePoint html table

It's been a while since I've posted anything, but I wanted to share a function that will take an html container or div control and print it to a new page. It will also grab the css files and output it to the head of the new page to maintain the styles when you print

This is dependent on the jquery library, found here:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>



//This function will grab the html from the container var to display in a new window.
//It also loads the css files that are on the current page and appends it to the output that is displayed in a new window to maintain the styles
//Title: Specify the title of the page that you wish to name when the print page opens
//Container: pass in the name of the container you wish to print. Ex. $("$tableName")
function PrintPage(title, container)
{
 //declare the css files with the styles you wish to grab and keep in the in the head of the new window
 var m_siteUrl = _spPageContextInfo.webServerRelativeUrl; //IE11 in sp 2013 does not recognize L_Menu_BaseUrl

 var curDate = new Date();
 var cssLink1 = m_siteUrl + "/siteassets/css/tablesorter/style.css?v=" + curDate.format("MM_dd_yyyy");
 var cssLink2 = m_siteUrl + "/siteassets/css/My_Page_Reports.css?v=" + curDate.format("MM_dd_yyyy");

 var divOutput = $(container).html();

 //append the current date/time to the output window  
 var printDateString = curDate.format("MM/dd/yyyy hh:mm tt");
 printDateString = "<div style='padding-bottom:10px;'>" + printDateString + "</div>";
 divOutput = printDateString + divOutput;
 
 var cssFile1 = $('<div></div>');
 var cssFile2 = $('<div></div>');

 //used for the callbacks
 var def1 = $.Deferred();
 var def2 = $.Deferred();      
   
 //loads the css files and grabs all of the css to input into style tags
 var cssFileText = "";
 cssFile1.load( cssLink1, function() { cssFileText += "<style>" + cssFile1.html() + "</style>"; def1.resolve()} );
 cssFile2.load( cssLink2, function() { cssFileText += "<style>" + cssFile2.html() + "</style>"; def2.resolve()} );

 //gets called asynchronously after the css files have been loaded
 $.when(def1, def2).done(function(){

 //generate the html that will be displayed in the new page.
 //set the title of the new window
 //additionally, can put the class names you wish to hide on printing  
   var html = "<HTML>\n" +
    "<HEAD>\n\n"+
    "<Title>" + title + "</Title>\n" +
    cssFileText + "\n" +
    "<style>"+
     ".hideOnPrint, .rowFilters {display:none}"+
    "</style>\n"+
   "</HEAD>\n" +
   "<BODY>\n" + divOutput + "\n" +"</BODY>\n" +
   "</HTML>";
 
 
   var printWP = window.open("","printWebPart");
   printWP.document.open();
   //insert content
   printWP.document.write(html);
     
   printWP.document.close();
   //open print dialog
   printWP.print();
  });  
}