Print a Part of Page using Javascript

do you want to print a part of the web page?

do you have multiple print buttons in a web page, which prints portion of the page?

do you want to exclude some elements in print of your page? (like images, ads)

do you want to print the display page differently? (changing font or colors of text)

Here, I am going to give code examples to above questions

Let us take a sample HTML web page

<html>
   <body>
       <div id="header">Header Content</div>
       <div id="content">actual content</div>
       <div id="footer">Footer content</div>
       <input type="button" value="Print" onclick="printPage();"></input>
  </body>
</html>

if you want to print the whole page then

<script language="javascript">
    function printPage() {
         window.print();
    }
</script>

To Print a part of the web page:
– create a print window and write html text you wanted to print
– focus the window and call the “print()” function
– close the print window

Here is the modified printPage function

<input type="button" value="Print" onclick="printPage('content');"></input>

function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;
   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
}

You can hide some of the elements within your actual content by adding style elements or include css file in print window html


  -----
 <div id="content">
   <div class="ads"> Ad content</div>
    actual content
   <img src="example.gif" />
</div>
 ----
function printPage(id)
{
   var html="<html>";
   html+="<head>";
   html+="<style type='text/css'>#content div.ads, #content img {display:none}</style>";
   html+="<link rel='Stylesheet' type='text/css' href='css/print.css' media='print' />";
   html+="</head>";
   html+= document.getElementById(id).innerHTML;
   html+="</html>";
    .....
}

In the above example, I have added style and css file, you can use either one or both. Using these styles or css, we can style the text only for print.

If you have multiple print buttons, and each one prints selected area of a web page, then you need to pass id of the print area on each button click.

<div id="area1">Area1 content</div>
<input type="button" value="Print" onclick="printPage('area1');"></input>
<div id="area2">Area2 content</div>
<input type="button" value="Print" onclick="printPage('area2');"></input>
15 Comments

Add a Comment

Your email address will not be published. Required fields are marked *