In this blog post, we will learn how to print in HTML using the JavaScript window.print() function. This function allows users to print the content of an HTML page directly from the browser.
Step 1: Create an HTML Button
First, we need to create an HTML button that will trigger the window.print() function when clicked. You can add the following code to your HTML file:
[sourcecode]
[/sourcecode]
Step 2: Add the JavaScript Function
Next, we need to create a JavaScript function called printPage() that will execute the window.print() function when the button is clicked. You can add the following script to your HTML file:
[sourcecode]
[/sourcecode]
Step 3: Test Your Print Button
Now it’s time to test the print button. When you click the button, a print dialog box should appear, allowing you to print the content of the page. You can try the button below:
Using CSS Media Queries for Print Styles
Sometimes, you may want to customize the appearance of your page when it’s printed. You can use CSS media queries to apply styles specifically for print. Add the following code to your CSS file or within a <style> tag in your HTML:
[sourcecode]
@media print {
/* Add your print-specific styles here */
body {
font-size: 12pt;
}
/* Example: Hide the print button when printing */
button {
display: none;
}
}
[/sourcecode]
This will ensure that your print styles are applied only when the page is being printed, and not when it’s displayed in the browser.
Conclusion
In this blog post, we learned how to print in HTML using the JavaScript window.print() function and how to customize the appearance of a printed page using CSS media queries. By following these simple steps, you can enable users to print your web pages with ease.