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

HTML Code:

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

No comments:

Post a Comment