views:

885

answers:

4

javascript code window.print() can print the current html page.

My question is: if I have a div in an html page(for example, a page rendered from ASP.NET MVC view), then I want to print the div only.

Is there any JQuery Unobtrusive javascrpt or normal javascript to implement this request?

Make it more clear. Suppose the rendered html page like:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head" runat="server">
<title>
        <asp:ContentPlaceHolder runat="server" ID="TitleContent" />
</title>
</head>
<body>
    <div id="div1" class="div1">....</div>
    <div id="div2" class="div2">....</div>
    <div id="div3" class="div3">....</div>
    <div id="div4" class="div4">....</div>    
    <div id="div4" class="div4">....</div>
<p>
    <input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
</p>
</body>
</html>

Then I want to click on the Print button only printing div3.

+2  A: 

You could use a print CSS stylesheet...

But this will affect all print functions.

You could try having a print stylesheet external, and it is included via Js when a button is pressed, and then call window.print(), then after that remove it.

alex
This would work, but with some modification to allow the page to "reset" after you've printed your target. (As you noted, this would be a problem.) For example, just before printing, open a modal window or some kind of overlay indicating that printing can now occur (or call window.print() right then) and then when user clicks OK or Close, the stylesheets can reset themselves.
Funka
Oh, also, you don't necessarily need to have an external CSS file loaded dynamically, you could have it pre-loaded but just adjust the classes on your target div or other container when ready to print. (And removing the classes when done.)
Funka
A: 

How about using canvas? Draw it onto a new window then calling the print() method from that new window?

You can find more documentation through here: drawWindow()

Paul
+1  A: 

I would go about it somewhat like this:

<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
    window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML
    window.frames["print_frame"].window.focus()
    window.frames["print_frame"].window.print()
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> <a href=javascript:printDiv('div1')>Print</a><br>
<div id=div1>This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href=javascript:printDiv('div2')>Print</a><br>
<div id=div2>This is the div2's print output</div>
<br><br>
<b>Div 3:</b> <a href=javascript:printDiv('div3')>Print</a><br>
<div id=div2>This is the div3's print output</div>
<iframe name=print_frame width=0 height=0 frameborder=0 src=about:blank></iframe>
</body>
</html>
Coding With Style
Thanks. This solution works fine.
KentZhou
But what's the propose of printDivCSS? It seems no need to use it.
KentZhou
printDivCSS is just there if you need to format what you're printing with a stylesheet. If you don't want your printed text to be formatted with a stylesheet, then you don't need it.
Coding With Style
This solution works fine in FF, but not work for IE 7. With IE7, it will print the entire page with blank for the wanted printing area
KentZhou
I checked what the situation was. IE7 will print the active frame by default, so I have to focus() the frame. It won't let me focus() "visibility: hidden" content, so I had to remove that bit of style formatting. The frame already has a width, height, and frameborder of 0, so it's hidden even without the style formatting. This way, everything works.Oh, one final note, if a user tries to CTRL+F search the page, it's possible that their search will find matches inside the frame, matches they can't see. You'll have to blank the frame after they are done printing to fix that one.
Coding With Style
Ah, just to be clear, I edited this answer with the updated code.
Coding With Style
+1  A: 

Along the same lines as some of the suggestions you would need to do at least the following:

  • Load some CSS dynamically through JavaScript
  • Craft some print-specific CSS rules
  • Apply your fancy CSS rules through JavaScript

An example CSS could be as simple as this:

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.

Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>
Zack Mulgrew
Thanks. It seems not working properly.
KentZhou
For FF, this solution will print the entire page with div3.For IE7, this solution will print the entire page but replace div3 with blank.
KentZhou
Which version of Firefox? When I tested this with IE it was with IE6 and it works correctly -- printing only "Div 3". Firefox 3.5.2 demonstrates the same behavior. Google Chrome 2.0.172.43 also demonstrates the same behavior. Maybe I don't understand your requirements.
Zack Mulgrew
THANKS. My scenario is: I put your suggest css @media print... into the site.css. My page is render as <body> <div class="fixed"> <div class="col1"> <div id="DivForPrint"> </div> </div> </div></body>maybe the css is not correct for this case?
KentZhou
It's hard to say without seeing the CSS and page source myself. Can you post it to somewhere like http://jsbin.com?
Zack Mulgrew