如何制作div的打印输出?

时间:2010-07-09 06:29:48

标签: javascript html printing-web-page

如何使用Javascript在我的页面中打印出特定的div?

4 个答案:

答案 0 :(得分:1)

我建议使用'print'css样式表,您可以在其中指定隐藏您不想打印的dom元素(使用display:none)。尝试仅在打印样式表中显示要打印的div。

另一种选择是使用弹出窗口,当单击页面中的“打印”按钮时显示该窗口。在弹出窗口中,仅显示div内容,并在文档加载时触发打印对话框。

答案 1 :(得分:0)

  

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

答案 2 :(得分:0)

这是一个已在Windows上的IE8和FF3.6.6中测试过的实现 有一些东西可以简化,但其他一些必要的(显示:iframe上的none将不打印任何内容)

<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>

答案 3 :(得分:-1)

Javascript不会打印。您必须将div插入DOM(文档对象模型)。

我建议学习一些jQuery并使用.append().prepend().html()函数。