【问题标题】:Print a div content using Jquery使用 Jquery 打印 div 内容
【发布时间】:2016-02-17 09:29:37
【问题描述】:

我想使用 jQuery 打印 div 的内容。这个问题已经在 SO 中提出,但我找不到正确的(工作)答案。

这是我的 HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>

这里我要打印 div printarea 的内容。

我试过了:

$("#btn").click(function () {
    $("#printarea").print();
});

但是单击按钮时会出现控制台错误:

未捕获的类型错误:$(...).print 不是函数

但是当我尝试使用打印整个页面时

window.print();

它正在工作。但我只想打印特定 div 的内容。我在很多地方看到了答案$("#printarea").print();,但这不起作用。

【问题讨论】:

  • 您可以设置一个带有media="print" 的样式表来隐藏所有不相关的内容。
  • 您实际上是在这里寻找 CSS 解决方案,this 是一个简单的设置,可以满足您的目的 - 它隐藏了除 .printable 类之外的所有页面元素
  • 如果您想获得好的答案,使用 JavaScript 标签可能是个好主意:meta.stackoverflow.com/questions/290244/…

标签: javascript jquery html printing


【解决方案1】:

上述解决方案都不能完美运行。它们要么丢失 CSS,要么必须包含/编辑外部 CSS 文件。我找到了一个完美的解决方案,既不会丢失您的 CSS,也不会编辑/添加外部 CSS。

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p

Javascript:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }

【讨论】:

  • 这也不适用于您的 css,在这里他只提供表格 css,因此您现在只能获取表格(基本)所有 css 元素。
  • 是的,这失去了所有的样式
【解决方案2】:

首先包含标题

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> 

<script type="text/JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.6.0/jQuery.print.js"></script>

由于您正在使用带有选择器的打印功能,该选择器是 print.js 的一部分,因此您需要在使用它之前调用它们...

Else 
    window.print()  

会做的

$("#btn").click(function () {
    $("#printarea").print();
});

$("#btn").on('click',function () {
    $("#printarea").print();
});

【讨论】:

    【解决方案3】:
    <div id='printarea'>
        <p>This is a sample text for printing purpose.</p> 
    </div>
    <input type='button' id='btn' value='Print' onlick="printDiv()">
    <p>Do not print.</p>
    
    function printDiv(){
            var printContents = document.getElementById("printarea").innerHTML;
            var originalContents = document.body.innerHTML;
            document.body.innerHTML = printContents;
            window.print();
            document.body.innerHTML = originalContents;
    }
    

    上面的这个函数应该在同一页面上加载。

    【讨论】:

      【解决方案4】:

      codepen 中的以下代码对我有用,

      function printData()
      {
         var divToPrint=document.getElementById("printTable");
         newWin= window.open("");
         newWin.document.write(divToPrint.outerHTML);
         newWin.print();
         newWin.close();
      }
      
      $('button').on('click',function(){
      printData();
      })
      

      这是一个链接codepen

      【讨论】:

      • 在 IE 中不起作用。对于 IE: var printContent = document.getElementById("PrintContent"); var windowUrl = '工作收据'; var uniqueName = new Date(); var windowName = '打印' + uniqueName.getTime(); var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0'); printWindow.document.write(printContent.innerHTML); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close();
      【解决方案5】:

      我更新了这个功能
      现在您可以使用完整样式打印任何标签或页面的任何部分
      必须包含 jquery.js 文件

      HTML

      <div id='DivIdToPrint'>
          <p>This is a sample text for printing purpose.</p>
      </div>
      <p>Do not print.</p>
      <input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >
      

      JavaScript

              function printtag(tagid) {
                  var hashid = "#"+ tagid;
                  var tagname =  $(hashid).prop("tagName").toLowerCase() ;
                  var attributes = ""; 
                  var attrs = document.getElementById(tagid).attributes;
                    $.each(attrs,function(i,elem){
                      attributes +=  " "+  elem.name+" ='"+elem.value+"' " ;
                    })
                  var divToPrint= $(hashid).html() ;
                  var head = "<html><head>"+ $("head").html() + "</head>" ;
                  var allcontent = head + "<body  onload='window.print()' >"+ "<" + tagname + attributes + ">" +  divToPrint + "</" + tagname + ">" +  "</body></html>"  ;
                  var newWin=window.open('','Print-Window');
                  newWin.document.open();
                  newWin.document.write(allcontent);
                  newWin.document.close();
                 // setTimeout(function(){newWin.close();},10);
              }
      

      【讨论】:

      • 这应该被标记为答案。我尝试了所有其他的东西,但都没有奏效。他们应该给你这个答案的奖章:)
      【解决方案6】:

      使用这个库:Print.JS

      使用此库,您可以打印 HTML 和 PDF。

      <form method="post" action="#" id="printJS-form">
          ...
       </form>
      
       <button type="button" onclick="printJS('printJS-form', 'html')">
          Print Form
       </button>
      

      【讨论】:

        【解决方案7】:

        一些 jQuery 研究失败了,所以我转向 JavaScript(感谢您的建议 Anders)。

        而且运行良好...

        HTML

        <div id='DivIdToPrint'>
            <p>This is a sample text for printing purpose.</p>
        </div>
        <p>Do not print.</p>
        <input type='button' id='btn' value='Print' onclick='printDiv();'>
        

        JavaScript

        function printDiv() 
        {
        
          var divToPrint=document.getElementById('DivIdToPrint');
        
          var newWin=window.open('','Print-Window');
        
          newWin.document.open();
        
          newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
        
          newWin.document.close();
        
          setTimeout(function(){newWin.close();},10);
        
        }
        

        【讨论】:

        • 你会丢失 CSS/JS/字体
        • 你不应该使用它,因为使用它之后你会丢失你的 JS。比如 $(".class").click() 和 $(".class").change 等事件。
        • 有时服务器超时而不显示打印窗口。
        • 这没有回答问题,您提供了替代解决方案。
        • 不是一个坏主意,相反,您应该使用“onload="window.print();window.close();”,它保证在打印/取消后关闭。因为计时器在您需要更长的时间才能对打印页面做出反应。
        【解决方案8】:

        Print only selected element on codepen

        HTML:

        <div class="print">
         <p>Print 1</p>
         <a href="#" class="js-print-link">Click Me To Print</a>
        </div>
        
        <div class="print">
         <p>Print 2</p>
         <a href="#" class="js-print-link">Click Me To Print</a>
        </div>
        

        jQuery:

        $('.js-print-link').on('click', function() {
          var printBlock = $(this).parents('.print').siblings('.print');
          printBlock.hide();
          window.print();
          printBlock.show();
        });
        

        【讨论】:

        • 如何将其更改为横向?
        【解决方案9】:

        我在这里尝试了所有非插件的方法,但都导致内容后打印空白页,或者有其他问题。这是我的解决方案:

        HTML:

        <body>
        <div id="page-content">        
            <div id="printme">Content To Print</div>
            <div>Don't print this.</div>
        </div>
        <div id="hidden-print-div"></div>
        </body>
        

        jquery:

            $(document).ready(function () {
                $("#hidden-print-div").html($("#printme").html());
            });
        

        CSS:

            #hidden-print-div {
                display: none;
            }
        
            @media print {
                #hidden-print-div {
                    display: block;
                }
        
                #page-content {
                    display: none;
                }
            }
        

        【讨论】:

          【解决方案10】:

          如果您想在没有额外插件的情况下执行此操作(例如printThis),我认为这应该可以。这个想法是有一个特殊的 div 将被打印,而其他所有内容都使用 CSS 隐藏。如果 div 是 body 标签的直接子级,这更容易做到,因此您必须将要打印的任何内容移动到这样的 div 中。 S 因此,首先创建一个 id 为 print-me 的 div 作为您的 body 标签的直接子代。然后使用此代码打印 div:

          $("#btn").click(function () {
              //Copy the element you want to print to the print-me div.
              $("#printarea").clone().appendTo("#print-me");
              //Apply some styles to hide everything else while printing.
              $("body").addClass("printing");
              //Print the window.
              window.print();
              //Restore the styles.
              $("body").removeClass("printing");
              //Clear up the div.
              $("#print-me").empty();
          });
          

          您需要的样式如下:

          @media print {
              /* Hide everything in the body when printing... */
              body.printing * { display: none; }
              /* ...except our special div. */
              body.printing #print-me { display: block; }
          }
          
          @media screen {
              /* Hide the special layer from the screen. */
              #print-me { display: none; }
          }
          

          我们应该只在printing 类存在时应用@print 样式的原因是,如果用户通过选择File -&gt; Print 打印页面,则页面应该正常打印。

          【讨论】:

            【解决方案11】:

            不使用任何插件,你可以选择这个逻辑。

            $("#btn").click(function () {
                //Hide all other elements other than printarea.
                $("#printarea").show();
                window.print();
            });
            

            【讨论】:

            • 在 Mozila firefox 上打印页面中的所有内容
            • 在 Chrome v.72 上打印页面中的所有内容。
            • 有一个 .container 类的 div,并且我在该 div 之外有某些元素,例如搜索栏和按钮,我不想在打印页面上显示它们。当我选择 $(".container").show() 时,它仍然会打印所有内容...
            【解决方案12】:

            看看这个 Plugin

            让您的代码像 -> $('SelectorToPrint').printElement();

            一样简单

            【讨论】:

              【解决方案13】:

              https://github.com/jasonday/printThis

              $("#myID").printThis();
              

              很棒的 Jquery 插件,可以完全满足您的需求

              【讨论】:

              猜你喜欢
              • 2011-06-23
              • 2013-07-19
              • 2020-03-24
              • 2015-09-28
              • 2011-01-16
              • 2021-09-13
              相关资源
              最近更新 更多