How to make a printout of a div?

How to print a specific div on my page using javascript?

+1
source share
4 answers

Here is an implementation that has been tested in IE8 and FF3.6.6 on windows. There are some things that can be ordered, but others that are needed (display: none of the iframe prints anything)

<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 document to null iFrame.doc = null; // Depending on browser platform get the iframe 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> 
0
source

I would suggest using the 'print' css stylesheet in which you can specify to hide dom elements that you don't want to print (with display: none). Try to make only the div you want to print in the print style sheet. A.

Another option is to use the pop-up window that appears when you click the print button on the page. In the pop-up window, only the contents of the div are displayed and the print dialog starts when the document is loaded.

+1
source

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

0
source

Javascript does not print. You should insert the div somewhere in the DOM (Document Object Model).

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

-1
source

All Articles