Printing a page with JavaScript can be achieved using the window.print() method. This method opens the print dialog box, which allows the user to choose the printer and settings.
Basic Syntax
javascript
window.print();
Example
Here's a simple example of how you can add a button to your web page that, when clicked, will trigger the print dialog:
html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Print Example</title></head><body><h1>Hello, World!</h1><p>This is a sample page to demonstrate printing with JavaScript.</p><buttononclick="window.print()">Print this page</button></body></html>
In this example:
The window.print() method is called when the button is clicked, which opens the print dialog.
Adding Print-Specific Styles
You can also define print-specific styles using the @media print CSS rule to ensure that your page looks good when printed.
html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Print Example with Styles</title><style>@media print {
body {
font-size: 14pt;
color: black;
}
h1 {
font-size: 18pt;
}
button {
display: none; /* Hide the print button when printing */
}
}
</style></head><body><h1>Hello, World!</h1><p>This is a sample page to demonstrate printing with JavaScript.</p><buttononclick="window.print()">Print this page</button></body></html>
In this example:
The @media print rule is used to apply styles only when the page is printed.
The print button is hidden using display: none; so it doesn't appear on the printed page.
Feel free to ask if you need more information or help with any specific use case!