Step by Step Tutorial: Print only a portion/part of page with javascript

Print-icon

There are many scenarios where you want to print just a section of a page and not the whole web page.
To achieve it first we should make sure that the web page is printout friendly.
I have shown below an example of how you can print just a section of a page and not the whole page.

In this example I have given an id to the portion which I want to print.
When an user click on print link a javascript function is called which actually plays the game.

First of all using jquery a window is opened, later it fetches the html data from the portion which is to be printed using its id and then sends it to popup which is opened.
We close the document, execute the print command and finally close the popup window.

<html>
<head>
<title>MyPHPscriptz.com - Print Selected Zone Tutorial</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function printthis()
{
 var w = window.open('', '', 'width=800,height=600,resizeable,scrollbars');
 w.document.write($("#printthis").html());
 w.document.close(); // needed for chrome and safari
 javascript:w.print();
 w.close();
 return false;
}
</script>
</head>
<body>
<div id="dontprintthis"><h1>This is something which i dont want to print</h1></div>
<div id="printthis"><h1>This is something which i want to print</h1></div>
<a href="printpage" onClick="printthis(); return false;">Print this page</a>
</body>
</html>

This is the whole process how you can print a portion of a page and not the whole page.

I hope this tutorial will help you lot.

Don’t forget to leave feedback/comments/questions.

7 Comments+ Add Comment

  • thanks

  • gr8 post…

  • nice..its working in chrome and others but not working in internet explorer.

    thanks and its very nice

  • This is very good, thanks! There’s one more think I’d like it to do, however – I want to choose more than one div to print. What it does now is only shows one of the divs that I’ve added the id=printthis, and ignores the other. Is there an adjustment to the code that will allow me to do that?

  • Gr8 but button prints too any way around that?

  • Thanks 4 the post. it really helps