To print a web page using JavaScript, you can use the window.print()
method. This method will open the print dialog box and allow the user to choose their print settings before printing the page.
Here’s an example of how to use window.print()
:
// Wait for the page to finish loading
window.onload = function() {
// Find the print button and add a click event listener
const printButton = document.getElementById("print-button");
printButton.addEventListener("click", function() {
// Call the window.print() method
window.print();
});
}
In this example, the script waits for the page to finish loading before finding the print button and adding a click event listener to it. When the button is clicked, the window.print()
method is called, which opens the print dialog box.
You can customize the print settings by adding options to the window.print()
method. For example, you can use the mediaPrint
option to only print the content that is visible on the screen:
window.print({
mediaPrint: true
});
You can also use CSS media queries to style the page specifically for printing. For example, you might want to hide certain elements or adjust the font size for better readability on paper:
@media print {
/* Styles for printing only */
body {
font-size: 14pt;
}
.no-print {
display: none;
}
}
In this example, the @media print
rule applies only to printing, and adjusts the font size of the body
element and hides any elements with the no-print
class.