There are two problems with this approach:
- You cannot print part of your HTML page
- If you have a print button to print the page , even the button shows up in the printed page.
To overcome this problem , here is a recipe to use window.print() efficiently:
STEP1: Create a HTML page with exactly the contents you want to print
STEP2: On onload() method of this html page body , call window.print() , so that when the page is loaded print functionality is triggered
STEP3: Place the print button on the page you want the user to trigger the print button.
STEP4: On click of the print button , open the html page that you created with the print contents (using window.open() method)
STEP5: Use the inbuilt onafterprint() method to close the print window once the print is completed (use window.close() method inside it).
Here is a demo :