Print <div id=printarea></div> only?

    |
  • Added:
  • |
  • In: Wordpress

How do I print the indicated div (without manually disabling all other content on the page)?

I want to avoid a new preview dialog, so creating a new window with this content is not useful.

The page contains a couple of tables, one of them contains the div I want to print - the table is styled with visual styles for the web, that should not show in print.

This Question Has 24 Answeres | Orginal Question | noesgard

With CSS 3 you could use the following:

body *:not(#printarea) { display: none; } 

I didn't really like any of these answers as a whole. If you have a class (say printableArea) and have that as an immediate child of body, then you can do something like this:

body > *:not(.printableArea) { display: none; } //Not needed if already showing body > .printableArea { display: block; } 

Using the visibility can cause a lot of spacing issues and blank pages. This is because the visibility maintains the elements space, just makes it hidden, where as display removes it and allows other elements to take up its space.

The reason why this solution works is that you are not grabbing all elements, just the immediate children of body and hiding them. The other solutions below with display css, hide all the elements, which effects everything inside of printableArea content.

I wouldn't suggest javascript as you would need to have a print button that the user clicks and the standard browser print buttons wouldn't have the same effect. If you really need to do that, what I would do is store the html of body, remove all unwanted elements, print, then add the html back. As mentioned though, I would avoid this if you can and use a CSS option like above.

Use a special Stylesheet for printing

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

and then add a class i.e. "noprint" to every tag which's content you don't want to print.

In the CSS use

.noprint { display: none; } 

hm ... use the type of a stylsheet for printing ... eg:

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

print.css:

div { display: none; } #yourdiv { display: block; } 

In my case I had to print a image inside a page. When I used the solution voted, I had 1 blank page and the other one showing the image. Hope it will help someone.

Here is the css I used:

@media print { body * { visibility: hidden; } #not-print * { display: none; } #to-print, #to-print * { visibility: visible; } #to-print { display: block !important; position: absolute; left: 0; top: 0; width: auto; height: 99%; } } 

My html is:

<div id="not-print" > <header class="row wrapper page-heading"> </header> <div class="wrapper wrapper-content"> <%= image_tag @qrcode.image_url, size: "250x250" , alt: "#{@qrcode.name}" %> </div> </div> <div id="to-print" style="display: none;"> <%= image_tag @qrcode.image_url, size: "300x300" , alt: "#{@qrcode.name}" %> </div> 

You could use a separate CSS style which disables every other content except the one with the id "printarea".

See CSS Design: Going to Print for further explanation and examples.

Could you use a print stylesheet, and use CSS to arrange the content you wanted printed? Read this article for more pointers.

Here is a general solution, using CSS only, which I have verified to work.

@media print { body * { visibility: hidden; } #section-to-print, #section-to-print * { visibility: visible; } #section-to-print { position: absolute; left: 0; top: 0; } } 

Alternative approaches aren't so good. Using display is tricky because if any element has display:none then none of its descendants will display either. To use it, you have to change the structure of your page.

Using visibility works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move section-to-print to the top left so it prints properly.

All the answers so far are pretty flawed - they either involve adding class="noprint" to everything or will mess up display within #printable.

I think the best solution would be to create a wrapper around the non-printable stuff:

<head> <style type="text/css"> #printable { display: none; } @media print { #non-printable { display: none; } #printable { display: block; } } </style> </head> <body> <div id="non-printable"> Your normal page contents </div> <div id="printable"> Printer version </div> </body> 

Of course this is not perfect as it involves moving things around in your HTML a bit...

The printDiv() function came out a few times, but in that case, you loose all your binding elements and input values. So, my solution is to create a div for everything called "body_allin" and another one outside the first one called "body_print".

Then you call this function:

function printDiv(divName){ var printContents = document.getElementById(divName).innerHTML; document.getElementById("body_print").innerHTML = printContents; document.getElementById("body_allin").style.display = "none"; document.getElementById("body_print").style.display = ""; window.print(); document.getElementById("body_print").innerHTML = ""; document.getElementById("body_allin").style.display = ""; document.getElementById("body_print").style.display = "none"; } 

The best way is by using css media="print"

The following code is really awesome and working.

<style media="print" type="text/css"> @media print { body * { visibility: hidden; } #PrintDiv * { visibility: visible; } #PrintDiv { position: absolute; top: 40px; left: 30px; } } </style> 

This code is working. I've tested this in Firefox 3.5.15

With jQuery it's as simple as this:

w=window.open(); w.document.write($('.report_left_inner').html()); w.print(); w.close(); 

I picked up the content using JavaScript and created a window that I could print in stead...

<script type="text/javascript"> function printDiv(divId) { var printContents = document.getElementById(divId).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = "<html><head><title></title></head><body>" + printContents + "</body>"; window.print(); document.body.innerHTML = originalContents; } </script> 

printDiv(divId): A generalized solution to print any div on any page.

I had a similar issue but I wanted (a) to be able to print the whole page, or (b) print any one of several specific areas. My solution, thanks to much of the above, allows you to specify any div object to be printed.

The key for this solution is to add an appropriate rule to the the print media style sheet so that the requested div (and its contents) will be printed.

First, create the needed print css to suppress everything (but without the specific rule to allow the element you want to print).

<style type="text/css" media="print"> body {visibility:hidden; } .noprintarea {visibility:hidden; display:none} .noprintcontent { visibility:hidden; } .print { visibility:visible; display:block; } </style> 

Note that I have added new class rules:

  • noprintarea allows you to suppress the printing of elements within your div- both the content and the block.
  • noprintcontent allows you to suppress the printing of elements within your div- the content is suppressed but and the allocated area is left empty.
  • print allows you to have items that show up in the printed version but not on the screen page. These will normally have "display:none" for the screen style.

Then insert three JavaScript functions. The first merely toggles the print media style sheet on and off.

function disableSheet(thisSheet,setDisabled) { document.styleSheets[thisSheet].disabled=setDisabled; } 

The second does the real work and the third cleans up afterward. The second (printDiv) activates the print media style sheet, then appends a new rule to allow the desired div to print, issues the print, and then adds a delay before the final housekeeping (otherwise the styles can be reset before the print is actually done.)

function printDiv(divId) { // Enable the print CSS: (this temporarily disables being able to print the whole page) disableSheet(0,false); // Get the print style sheet and add a new rule for this div var sheetObj=document.styleSheets[0]; var showDivCSS="visibility:visible;display:block;position:absolute;top:30px;left:30px;"; if (sheetObj.rules) { sheetObj.addRule("#"+divId,showDivCSS); } else { sheetObj.insertRule("#"+divId+"{"+showDivCSS+"}",sheetObj.cssRules.length); } print(); // need a brief delay or the whole page will print setTimeout("printDivRestore()",100); } 

The final functions deletes the added rule and sets the print style again to disabled so the whole page can be printed.

function printDivRestore() { // remove the div-specific rule var sheetObj=document.styleSheets[0]; if (sheetObj.rules) { sheetObj.removeRule(sheetObj.rules.length-1); } else { sheetObj.deleteRule(sheetObj.cssRules.length-1); } // and re-enable whole page printing disableSheet(0,true); } 

The only other thing to do is to add one line to your onload processing so that the print style is initially disabled thereby allowing whole page printing.

<body onLoad='disableSheet(0,true)'> 

Then, from anywhere in your document, you can print a div. Just issue printDiv("thedivid") from a button or whatever.

A big plus for this approach it provides a general solution to printing selected content from within a page. It also allows use of existing styles for elements that are printed - including the containing div.

NOTE: In my implementation, this must be the first style sheet. Change the sheet references (0) to the appropriate sheet number if you need to make it later in the sheet sequence.

I have a better solution with minimal code.

Place your printable part inside a div with an id like this:

<div id="printableArea"> <h1>Print me</h1> </div> <input type="button" onclick="printDiv('printableArea')" value="print a div!" /> 

Then add an event like an onclick (as shown above), and pass the id of the div like I did above.

Now let's create a really simple javascript:

function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } 

Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print").

No fluff, lightweight, it just works.

This works well:

<style type="text/css"> @media print { body * { visibility: hidden; } #printcontent * { visibility: visible; } #printcontent { position: absolute; top: 40px; left: 30px; } } </style> 

Note that this only works with "visibility". "display" won't do it. Tested in FF3.

You can use this: http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/

Or use visibility:visible and visibility:hidden css property together with @media print{}

'display:none' will hide all nested 'display:block'. That is not solution.

@Kevin Florida If you have multiple divs with same class, you can use it like this:

 <div style="display:none"> <div id="modal-2" class="printableArea"> <input type="button" class="printdiv-btn" value="print a div!" /> </div> </div> 

i was using Colorbox inner content type

$(document).on('click', '.printdiv-btn', function(e) { e.preventDefault(); var $this = $(this); var originalContent = $('body').html(); var printArea = $this.parents('.printableArea').html(); $('body').html(printArea); window.print(); $('body').html(originalContent); }); 

Sandro's method works great.

I tweaked it to allow for allowing multiple printMe links, particularily to be used in tabbed pages and expanding text.

function processPrint(printMe){ <-- calling for a variable here

var printReadyElem = document.getElementById(printMe); <-- removed the quotes around printMe to ask for a variable

<a href="javascript:void(processPrint('divID'));">Print</a> <-- passing the div ID to be printed on to the function to turn the printMe variable into the div ID. single quotes are needed

If you only want to print this div, you must use the instruction:

@media print{ *{display:none;} #mydiv{display:block;} } 
  1. Give whatever element you want to print the id printMe.

  2. Include this script in your head tag:

    <script language="javascript"> var gAutoPrint = true; function processPrint(){ if (document.getElementById != null){ var html = '<HTML>\n<HEAD>\n'; if (document.getElementsByTagName != null){ var headTags = document.getElementsByTagName("head"); if (headTags.length > 0) html += headTags[0].innerHTML; } html += '\n</HE' + 'AD>\n<BODY>\n'; var printReadyElem = document.getElementById("printMe"); if (printReadyElem != null) html += printReadyElem.innerHTML; else{ alert("Error, no contents."); return; } html += '\n</BO' + 'DY>\n</HT' + 'ML>'; var printWin = window.open("","processPrint"); printWin.document.open(); printWin.document.write(html); printWin.document.close(); if (gAutoPrint) printWin.print(); } else alert("Browser not supported."); } </script> 
  3. Call the function

    <a href="javascript:void(processPrint());">Print</a> 

I had multiple images each with a button and needed to click on a button to print each div with an image. This solution works if I have disabled cache in my browser, and the image size doesn't change in Chrome:

 function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; w = window.open(); w.document.write(printContents); w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>'); w.document.close(); // necessary for IE >= 10 w.focus(); // necessary for IE >= 10 return true; } <div id="printableArea"> <h1>Print me</h1> </div> <input type="button" onclick="printDiv('printableArea')" value="print a div!" /> 

Step1. Write the following javascript inside your head tag

<script language="javascript"> function PrintMe(DivID) { var disp_setting="toolbar=yes,location=no,"; disp_setting+="directories=yes,menubar=yes,"; disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25"; var content_vlue = document.getElementById(DivID).innerHTML; var docprint=window.open("","",disp_setting); docprint.document.open(); docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'); docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'); docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">'); docprint.document.write('<head><title>My Title</title>'); docprint.document.write('<style type="text/css">body{ margin:0px;'); docprint.document.write('font-family:verdana,Arial;color:#000;'); docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}'); docprint.document.write('a{color:#000;text-decoration:none;} </style>'); docprint.document.write('</head><body onLoad="self.print()"><center>'); docprint.document.write(content_vlue); docprint.document.write('</center></body></html>'); docprint.document.close(); docprint.focus(); } </script> 

Step2. Call the PrintMe('DivID') function by an onclick event.

<input type="button" name="btnprint" value="Print" onclick="PrintMe('divid')"/> <div id="divid"> here is some text to print inside this div with an id 'divid' </div> 

Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns
Top