Advantages
- Your page retains interactivity after print
- Plays nice with frameworks
- Doesn't require duplicating your UI for print
Steps
- Hide every content of the page when in print mode
- Make your target element visible in print mode
Step 1
@media print {
body {
visibility: hidden;
}
}
Step 2
@media print {
#section-to-print {
top: 0;
left: 0;
position: absolute;
visibility: visible;
}
}
Then print
const button = document.querySelector('print-page');
button.addEventListener('click', () => window.print());
This method avoids the pitfall of loosing interactivity, other methods replace the entire page content with the static HTML thereby loosing interactivity.
const printContents = document.getElementById(divId).innerHTML;
const originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;