Send DIV contents to printer, print div contents

456 0 0 0

Last Updated : 2024-04-29 08:13:08

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>

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .