Printing Specific HTML Content on Button Click Without Including Full Webpage
Printing only specific HTML content upon a user's button click can be achieved in various ways. One method is to create a hidden div element to hold the desired HTML. This div should have its display property set to 'print' for printing purposes, while its display value remains 'none' for screen display. Other elements on the page can have their display properties adjusted to show on screen but hide during printing. This method, however, requires meticulous management of all page elements' display properties.
An alternative approach is to create a new, isolated webpage containing solely the HTML content to be printed. This new page can be dynamically loaded into a hidden iframe when the user clicks the print button. Once the iframe has fully loaded, the browser's print function can be triggered, and the embedded HTML will be printed without any unwanted page elements. This method offers greater flexibility and dynamic control over the printing process.
Here's an example using the second approach:
// Create an invisible iframe to hold the print-only HTML
const printFrame = document.createElement('iframe');
printFrame.style.display = 'none';
document.body.appendChild(printFrame);
// Dynamically load the print-only HTML into the iframe
printFrame.onload = function() {
// Trigger the browser's print function once the print-only page is loaded
window.print();
}
printFrame.src = 'print-only.html';
This solution allows you to print specific HTML content conveniently upon button click without modifying the main webpage's appearance or content. It ensures that only the intended HTML is printed, providing a more user-friendly printing experience.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3