Search code examples
javascriptsharepointcewp

CEWP Print Button with Code to print SharePoint form?


I currently have a Preview of our form that looks exactly how we want it to look for the list item being viewed but the problem is when I added my Print button as CEWP in FOrm Display it performs the exact same function as using Control P and prints the entire page. See code.

          <div style="text-align: center"><input onclick="window.print();return false;" type="button" value=" Print this page "/>&#160;</div>"

I want to add onto this to have it only print the form and no other content out side of the current view in the window and actually fill an 8.5 by 11.

Any ideas?


Solution

  • Inspired by this InfoPath print button, one solution would be to grab the contents of your CEWP and create a new window that only contains those.

    var patt = /**your CEWP ID here***/g;
    var alldivs = document.getElementsByTagName('div');
    var printpageHTML = '';
    for(var i=0; i<alldivs.length; i++){
      if(patt.test(alldivs[i].id)){
        printpageHTML = '<HTML><HEAD>\n' +
          document.getElementsByTagName('HEAD')[0].innerHTML +
          '</HEAD>\n<BODY>\n' + 
          alldivs[i].innerHTML.replace('inline-block','block') + 
          '\n</BODY></HTML>';
        break;
      }
    }
    var printWindow = window.open('','printWindow');
    printWindow.document.open();
    printWindow.document.write(printpageHTML);
    printWindow.document.close();
    printWindow.print();
    printWindow.close();
    

    Fixed: removed escaping for HTML characters.