views:

1584

answers:

5

Hi all,

I have particular division in my web page. i want to print that div only when click "print" in my web page. i have some javascript code. But that is not well formatted.

Is there any javascript to print particular division from my web page?

Thanks in advance

  • Gnaniyar Zubair
A: 

I don't think there is a direct way of doing this. You can however:

  • Create a special CSS for media=print where all but the one div you want to print is hidden, OR
  • Use a hidden iframe for the content you want to print

Googling with the terms "javascript print partial page" may help you find some tutorials.

dirkgently
CSS would be the better option.
Steve Harrison
Sure, but I have seen pages use iframes as well, mentioned it for the sake of completeness.
dirkgently
+9  A: 

You can specify CSS stylesheets with the attribute media="print" and apply the style display: none; to all elements except those which you want printed.

For example:

print.css

* { display: none; }
div.print_block { display: block; }

page.html

<HEAD>
<LINK rel="stylesheet" type="text/css" 
     media="print" href="print.css" />
</HEAD>

<DIV class="print_block">
   ...
</DIV>
Andy
thanks andy... then in print button onclick i have to give onclick='window.print()'. then it will print only that div. right?
Gnaniyar Zubair
Yes, though the JavaScript isn't really relevant; the same will happen when the user goes to File->Print themselves.
bobince
Yep. It applies the media="print" styles. You can test this without printing by changing the tag to media="screen" instead (making sure it's the last style sheet referenced.
Andy
+3  A: 

If you want to hide some divs when printing, you can set them to "display: none" in a print media section of your stylesheet, and they won't appear.

eg, in your stylesheet:

 @media print {

    div.header {
        display: none;
    }

    div.printable {
        page-break-inside: avoid;
        page-break-after: always;
    }
 }

This answer is almost exactly the same as the two which beat me by 4 minutes :-) , just a note that you don't need a whole separate stylesheet if you don't want to ...

Also, the "page-break-inside: avoid;" and "page-break-after: always;" clauses are good for printing out a few divs, each on its own page.

Sharkey
A: 

I saw smf like that in one project at my job. You have to open popup in popup you put content from parent page which you wanna to print. And it's all :)

lfx
+1  A: 

Check this jQuery plugin jqPrint. It seems to do what you want.

tanathos