Printing HTML Content Selectively on Button Click
Web developers often encounter the need to allow users to print specific sections of a web page without including the entire page content. In this context, the question arises:
How can we print only selected HTML content when a button is clicked, excluding the rest of the page?
Solution:
The suggested solution to keep the hidden HTML content in a display: print div is a valid approach. However, there is a simpler and more efficient method:
Create a Print Stylesheet:
<code class="css">@media print { .noPrint { display: none; } }</code>
This code will hide elements with the class "noPrint" when the page is printed.
Identify the HTML content that should not be printed and add the class "noPrint" to these elements, such as:
<code class="html"><h1 class="noPrint">No Print</h1></code>
Add the following line to the
section of your HTML document:<code class="html"><link rel="stylesheet" href="print.css" media="print"></code>
Create a button that triggers the print dialog when clicked:
<code class="html"><button onclick="window.print()">Print</button></code>
Explanation:
When the print button is clicked, the window.print() method is called, opening the browser's print dialog. The CSS media query @media print { ... } is triggered, causing the elements with the class "noPrint" to be hidden. As a result, only the desired HTML content is printed.
The above is the detailed content of How to Print Only Selected HTML Content on Button Click?. For more information, please follow other related articles on the PHP Chinese website!