How can I print only one component on click of a button.
I know this solution:
window.frames[\"print_frame\"].window.focus();
window.frames[\"print
The solution provided by Emil Ingerslev is working fine, but CSS is not applied to the output. Here I found a good solution given by Andrewlimaza. It prints the contents of a given div, as it uses the window object's print method, the CSS is not lost. And there is no need for an extra iframe also.
var printContents = document.getElementById("divcontents").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
Update 1: There is unusual behavior, in chrome/firefox/opera/edge, the print or other buttons stopped working after the execution of this code.
Update 2: The solution given is there on the above link in comments:
.printme { display: none;}
@media print {
.no-printme { display: none;}
.printme { display: block;}
}
<h1 class = "no-printme"> do not print this </h1>
<div class='printme'>
Print this only
</div>
<button onclick={window.print()}>Print only the above div</button>
You'll have to style your printout with @media print {}
in the CSS but the simple code is:
export default class Component extends Component {
print(){
window.print();
}
render() {
...
<span className="print"
onClick={this.print}>
PRINT
</span>
}
}
Hope that's helpful!