How do I print the indicated div (without manually disabling all other content on the page)?
I want to avoid a new preview dialog, so creating a new window with this
With jQuery it's as simple as this:
w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();
Best css to fit space empty height:
@media print {
body * {
visibility: hidden;
height:0;
}
#section-to-print, #section-to-print * {
visibility: visible;
height:auto;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
You could use a separate CSS style which disables every other content except the one with the id "printarea".
See CSS Design: Going to Print for further explanation and examples.
One more approch without affecting current page and it also persist the css while printing. Here selector must be specific div selector which content we need to print.
printWindow(selector, title) {
var divContents = $(selector).html();
var $cssLink = $('link');
var printWindow = window.open('', '', 'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth * 0.6);
printWindow.document.write('<html><head><h2><b><title>' + title + '</title></b></h2>');
for(var i = 0; i<$cssLink.length; i++) {
printWindow.document.write($cssLink[i].outerHTML);
}
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.onload = function () {
printWindow.focus();
setTimeout( function () {
printWindow.print();
printWindow.close();
}, 100);
}
}
Here provided some time out show that external css get applied to it.
With CSS 3 you could use the following:
body *:not(#printarea) {
display: none;
}
Use a special Stylesheet for printing
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
and then add a class i.e. "noprint" to every tag which's content you don't want to print.
In the CSS use
.noprint {
display: none;
}