I want to print some HTML content, when the user clicks on a button. Once the user clicks on that button, the print dialog of the browser will open, but it will not print the webpage. Instead, it will print the some other HTML content which is not displayed on the page.
While asking this question, there are few solutions coming into my mind. But I am not sure whether those are good ideas or something better can be done. One of those solutions are:
I can keep this HTML content in a div and make it display:
to print, but display: none
to screen. All other elements on the webpage can be made to display: none
for print and display:
for the screen. And then call to print.
Any better idea?
I came across another elegant solution for this:
Place your printable part inside a div with an id like this:
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
Now let's create a really simple javascript:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
SOURCE : SO Answer