594 0 0 0
Last Updated : 2025-04-28 21:26:33
Sometimes you will need to print/send the contents of a div to the printer using JS, here is the code for both HTML and JS
HTML CODE :
<div id='DivIdToPrint' style='border: 1px solid gray; background-color: lightgreen; padding: 20px;'>
<p style='padding: 10px; margin: 0px;'>
THE CONTENT GOES HERE
</p>
</div>
<input type='button' id='btn' value='Print' onclick='printDiv();' >
JS CODE :
<script>
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
</script>