@media print {
body * {
visibility: hidden;
}
#section-to-print, #section-to-print * {
visibility: visible;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
// It's really that simple. Make sure the dimensions of 'elem'
// fit the width of the PDF layout you're looking for.
// FYI: IE, Edge, Chrome, Firefox, etc. all have different dimensions when
// they print.
function PrintElem(elem: HTMLElement)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write(elem.innerHTML);
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
setTimeout(() => {
// Without the timeout, the window seems to close immediately.
mywindow.close();
}, 250);
}
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />