This is a revised solution that will also work for modal windows rendered using a Grails template, where you can have the same modal template called multiple times (with different values) in the same body. This thread helped me immensely, so I thought I'd share it in case other Grails users found their way here.
For those who are curious, the accepted solution didn't work for me because I am rendering a table; each row has a button that opens a modal window with more details about the record. This led to multiple printSection divs being created and printed on top of each other. Therefore I had to revise the js to clean up the div after it was done printing.
CSS
I added this CSS directly to my modal gsp, but adding it to the parent has the same effect.
<style type="text/css">
@media screen {
#printSection {
display: none;
}
}
@media print {
body > *:not(#printSection) {
display: none;
}
#printSection, #printSection * {
visibility: visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
</style>
Adding it to the site-wide CSS killed the print functionality in other parts of the site. I got this from ComFreak's accepted answer (based on Bennett McElwee answer), but it is revised using ':not' functionality from fanfavorite's answer on Print <div id=printarea></div> only? . I opted for 'display' rather than 'visibility' because my invisible body content was creating extra blank pages, which was unacceptable to my users.
js
And this to my javascript, revised from ComFreak's accepted answer to this question.
function printDiv(div) {
// Create and insert new print section
var elem = document.getElementById(div);
var domClone = elem.cloneNode(true);
var $printSection = document.createElement("div");
$printSection.id = "printSection";
$printSection.appendChild(domClone);
document.body.insertBefore($printSection, document.body.firstChild);
window.print();
// Clean up print section for future use
var oldElem = document.getElementById("printSection");
if (oldElem != null) { oldElem.parentNode.removeChild(oldElem); }
//oldElem.remove() not supported by IE
return true;
}
I had no need for appending elements, so I removed that aspect and changed the function to specifically print a div.
HTML (gsp)
And the modal template. This prints the modal header & body and excludes the footer, where the buttons were located.
<div class="modal-content">
<div id="print-me"> <!-- This is the div that is cloned and printed -->
<div class="modal-header">
<!-- HEADER CONTENT -->
</div>
<div class="modal-body">
<!-- BODY CONTENT -->
</div>
</div>
<div class="modal-footer">
<!-- This is where I specify the div to print -->
<button type="button" class="btn btn-default" onclick="printDiv('print-me')">Print</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I hope that helps someone!