Monday, December 30, 2013

Print HTML Div content using JavaScript

Well it's very easy to implement the print functionality using JavaScript. I have provided two kind of code. Try it.

JavaScript Code 1:
  1. function PrintFunction1(divId) {
  2.     var divElements = document.getElementById(divId).innerHTML;
  3.     var oldPage = document.body.innerHTML;
  4.     document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
  5.     window.print();
  6.     document.body.innerHTML = oldPage;
  7. }
JavaScript Code 2:
  1. function PrintFunction2(divId)
  2. {
  3.     var DocumentContainer = document.getElementById(divId);
  4.     var WindowObject = window.open('', "PrintWindow", "width=800,height=600,top=45,left=45,toolbars=no,scrollbars=yes,status=no,resizable=yes");
  5.     WindowObject.document.writeln(DocumentContainer.innerHTML);
  6.     WindowObject.document.close();
  7.     WindowObject.focus();
  8.     WindowObject.print();
  9.     WindowObject.close();
  10. }

HTML Code:

<a href="#" onclick="javascript:PrintFunction1('DivToPrint')">Print</a>
<div id="DivToPrint">
// --------------
// -------------
//Contents to be print
//---------------
// -------------
</div>

No comments:

Post a Comment