1

How do I print out a particular div in my page using Javascript?

3
  • 11
    plz be more specific Commented Jul 9, 2010 at 6:30
  • 2
    hello friend, do you want to take the printout or a soft copy ? Commented Jul 9, 2010 at 6:32
  • Is there any reason you want to "print" a div with javascript? Commented Jul 9, 2010 at 6:34

4 Answers 4

1

I would suggest using a 'print' css stylesheet, in which you can specify to hide the dom elements you do not want to print (with display: none). Try to only make the div you want to print visible in the print stylesheet.

Another option would be to use a popup window that displays when clicked on the 'print' button in the page. In the popup window only display the div contents, and trigger a print dialog on document load.

Sign up to request clarification or add additional context in comments.

1 Comment

Nothing beats a print stylesheet.
0

Here is an implementation that has been tested in IE8 and FF3.6.6 on windows There are some stuff that can be streamlined, but other that are necessary (display:none on the iframe will print nothing)

<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
  <title>print selected paragraphs</title>
  <style>
  a{text-decoration:none}
  </style>

  <style media="print">
  .noPrint { display:none}
  .print { display:block}
  </style>
  <script>
  function addPrint() {
    var checks = document.getElementsByTagName('input');
    for (var i=0;i<checks.length;i++) {
      document.getElementById(checks[i].value).className = (checks[i].checked)?'print':'noPrint';
    }
  }
  var content
  function printThis(id) {
    var iFrame = document.createElement('iframe');
    iFrame.height='1px';
    iFrame.width='1px';
    content = document.getElementById(id).innerHTML;
    content = '<body onload="self.focus();self.print()"><style>.noprint{display:none}</style>'+content+'</body>'
    iFrame.src='about:blank';
    document.body.appendChild(iFrame);
   // Initiate the iframe's document to null
     iFrame.doc = null;

     // Depending on browser platform get the iframe's document, this is only
     // available if the iframe has already been appended to an element which
     // has been added to the document
     if(iFrame.contentDocument)
      // Firefox, Opera
      iFrame.doc = iFrame.contentDocument;
     else if(iFrame.contentWindow)
      // Internet Explorer
      iFrame.doc = iFrame.contentWindow.document;
     else if(iframe.document)
      // Others?
      iFrame.doc = iFrame.document;

     // If we did not succeed in finding the document then throw an exception
     if(iFrame.doc != null) {
      iFrame.doc.write(content)
      iFrame.doc.close()
    }
    return false
  }
  window.onload=function() {
    addPrint();
  }
  </script>
  </head>
  <body>
<div id="p1" class="noPrint">
<h3>1. ¿Qué es Lorem Ipsum?</h3>
<p>Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.</p>
<input type="checkbox" class="noPrint" id="c1" value="p1" onClick="addPrint(this)"><label class="noPrint" for="c1">Add this to print</label>&nbsp;<a href="#" onClick="return printThis('p2')">Print this NOW</a>
</div>

<div id="p2" class="noPrint">
<h3>2. ¿Por qué lo usamos?</h3>
<p>Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". Estos textos hacen parecerlo un español que se puede leer. Muchos paquetes de autoedición y editores de páginas web usan el Lorem Ipsum como su texto por defecto, y al hacer una búsqueda de "Lorem Ipsum" va a dar por resultado muchos sitios web que usan este texto si se encuentran en estado de desarrollo. Muchas versiones han evolucionado a través de los años, algunas veces por accidente, otras veces a propósito (por ejemplo insertándole humor y cosas por el estilo).</p>
<input type="checkbox" class="noPrint" id="c2" value="p2" onClick="addPrint(this)"><label class="noPrint" for="c2">Add this to Print</label>
</div>
</body>
</html>

Comments

0

document.write('<div>' + variableWithSomeContent + '</div>');

Comments

-1

Javascript doesn't print. You have to insert the div somewhere into the DOM (Document Object Model).

I suggest learning some jQuery and using the .append(), .prepend() or .html() functions.

2 Comments

Learning jQuery before even having a basic understanding of Javascript/DOM/etc is a recipe for problems IMO
how hard can it be to print just a div with Javascript for you? cause you really have to learn jQuery... :) are you serious?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.