【问题标题】:Print the contents of a DIV打印 DIV 的内容
【发布时间】:2011-01-16 08:26:32
【问题描述】:

打印 DIV 内容的最佳方式是什么?

【问题讨论】:

标签: javascript jquery html printing


【解决方案1】:

最好的方法是将 div 的内容提交到服务器并打开一个新窗口,服务器可以将这些内容放入新窗口中。

如果这不是一个选项,您可以尝试使用 javascript 之类的客户端语言来隐藏页面上除该 div 之外的所有内容,然后打印页面...

【讨论】:

  • 不需要反弹到服务器。您可以打开浏览器窗口并设置内容并调用打印命令。
  • 您可以从客户端创建一个新窗口。
  • Jonathon:我喜欢那个解决方案。有示例代码吗?
【解决方案2】:

创建一个单独的打印样式表,隐藏除您要打印的内容之外的所有其他元素。加载时使用'media="print" 标记它:

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

这允许您为打印输出加载完全不同的样式表。

如果你想强制浏览器的打印对话框出现在页面上,你可以使用 JQuery 在加载时这样做:

$(function() { window.print(); });

或触发您想要的任何其他事件,例如用户单击按钮。

【讨论】:

  • 是的,那也可以;很难 - 嗯,不可能 - 确切地知道场景是什么。
  • 我同意单独的 CSS 是理想的解决方案。将 div 的内容复制到新窗口是一种快速的解决方案。
【解决方案3】:
  • 打开一个新窗口
  • 打开新窗口的文档对象,并在其中写入一个简单的文档,其中只包含您拥有的 div 和必要的 html 标题等 - 您可能还希望将文档拉入样式表,具体取决于您的内容是
  • 在新页面中放一个脚本调用window.print()
  • 触发脚本

【讨论】:

    【解决方案4】:

    与早期版本相比略有变化 - 在 CHROME 上测试

    function PrintElem(elem)
    {
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');
    
        mywindow.document.write('<html><head><title>' + document.title  + '</title>');
        mywindow.document.write('</head><body >');
        mywindow.document.write('<h1>' + document.title  + '</h1>');
        mywindow.document.write(document.getElementById(elem).innerHTML);
        mywindow.document.write('</body></html>');
    
        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10*/
    
        mywindow.print();
        mywindow.close();
    
        return true;
    }
    

    【讨论】:

    • 这是一个快速的解决方案。理想的解决方案是使用单独的 CSS 进行打印。也许您可以详细说明您的问题的细节(要求)。
    • 您可以在弹出窗口中引用样式表。在 标记之间添加另一行代码: mywindow.document.write('');
    • @Rahil 将其更改为:mywindow.document.close(); mywindow.focus(); mywindow.print(); mywindow.close();
    • ^ 添加 newwindow.focus();启用跨浏览器打印。
    • 如果无法加载打印预览有时会发生这种情况,可能是当要打印的内容很大时(我注意到它只在 Chrome 中,而同一页面在 Firefox 中打印完美,但我不排除它可能发生在Firefox 或其他浏览器)。我发现的最好方法是仅在加载 Windows 后运行打印(并关闭)。所以之后:mywindow.document.write(data); 添加这个:mywindow.document.write('&lt;script type="text/javascript"&gt;$(window).load(function() { window.print(); window.close(); });&lt;/script&gt;'); 并删除:mywindow.print();mywindow.close();
    【解决方案5】:

    虽然@gabe已经说过了, 如果你使用 jQuery,你可以使用我的 printElement 插件。

    有一个示例here,以及有关插件here 的更多信息。

    用法相当简单,只需使用 jQuery 选择器抓取一个元素并打印它:

    $("#myDiv").printElement();
    

    希望对你有帮助!

    【讨论】:

    • 8 年后,这将产生“a.browser is undefined”,因为 .browser 调用已在 jquery 1.9 中删除
    • 我的 printElement 未定义
    【解决方案6】:

    我认为有更好的解决方案。让您的 div 打印覆盖整个文档,但仅限于打印时:

    @media print {
        .myDivToPrint {
            background-color: white;
            height: 100%;
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
            margin: 0;
            padding: 15px;
            font-size: 14px;
            line-height: 18px;
        }
    }
    

    【讨论】:

    • 完美,比弹出窗口好得多。
    • 不幸的是,它在 IE 中无法正常工作,请参阅:stackoverflow.com/questions/975129/…
    • 应该溢出到多个页面的内容在 Chrome 中似乎被截断了。
    • 在 IE 上,您需要隐藏文档的其余部分。上面的修改如下:@media print { body * { display:none; } .myDivToPrint { 显示:块;背景颜色:白色;高度:100%;宽度:100%;位置:固定;顶部:0;左:0;边距:0;填充:15px;字体大小:14px;行高:18px; } }
    • 你可能需要把 z-index: 9999999;以防您将其他元素定位得更高。
    【解决方案7】:

    从这里https://forums.asp.net/t/1261525.aspx

    <html> 
    <head>
        <script language="javascript">
            function printdiv(printpage) {
                var headstr = "<html><head><title></title></head><body>";
                var footstr = "</body>";
                var newstr = document.all.item(printpage).innerHTML;
                var oldstr = document.body.innerHTML;
                document.body.innerHTML = headstr + newstr + footstr;
                window.print();
                document.body.innerHTML = oldstr;
                return false;
            }
        </script>
    
        <title>div print</title>
    
    </head>
    
    <body>
        //HTML Page //Other content you wouldn't like to print
        <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">
    
        <div id="div_print">
            <h1 style="Color:Red">The Div content which you want to print</h1>
        </div>
        //Other content you wouldn't like to print //Other content you wouldn't like to print
    </body>    
    </html>
    

    【讨论】:

    • 需要修改将 footerStr 拆分为 2 部分。因为浏览器使用“
    【解决方案8】:

    这是我的 jquery 打印插件

    (function ($) {
    
    $.fn.printme = function () {
        return this.each(function () {
            var container = $(this);
    
            var hidden_IFrame = $('<iframe></iframe>').attr({
                width: '1px',
                height: '1px',
                display: 'none'
            }).appendTo(container);
    
            var myIframe = hidden_IFrame.get(0);
    
            var script_tag = myIframe.contentWindow.document.createElement("script");
            script_tag.type = "text/javascript";
            script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
            script_tag.appendChild(script);
    
            myIframe.contentWindow.document.body.innerHTML = container.html();
            myIframe.contentWindow.document.body.appendChild(script_tag);
    
            myIframe.contentWindow.Print();
            hidden_IFrame.remove();
    
        });
    };
    })(jQuery);
    

    【讨论】:

      【解决方案9】:
      function printdiv(printdivname) {
          var headstr = "<html><head><title>Booking Details</title></head><body>";
          var footstr = "</body>";
          var newstr = document.getElementById(printdivname).innerHTML;
          var oldstr = document.body.innerHTML;
          document.body.innerHTML = headstr+newstr+footstr;
          window.print();
          document.body.innerHTML = oldstr;
          return false;
      }
      

      这将打印您想要的div 区域并将内容设置回原样。 printdivname 是要打印的div

      【讨论】:

      • 需要修改将 footerStr 拆分为 2 部分。因为浏览器使用“
      【解决方案10】:

      我知道这是一个老问题,但我用 jQuery 解决了这个问题。

      function printContents(id) {
          var contents = $("#"+id).html();
      
          if ($("#printDiv").length == 0) {
            var printDiv = null;
            printDiv = document.createElement('div');
            printDiv.setAttribute('id','printDiv');
            printDiv.setAttribute('class','printable');
            $(printDiv).appendTo('body');
          }
      
          $("#printDiv").html(contents);
      
          window.print();
      
          $("#printDiv").remove();
      }
      

      CSS

        @media print {
          .non-printable, .fancybox-outer { display: none; }
          .printable, #printDiv { 
              display: block; 
              font-size: 26pt;
          }
        }
      

      【讨论】:

        【解决方案11】:

        在 Opera 中,尝试:

            print_win.document.write('</body></html>');
            print_win.document.close(); // This bit is important
            print_win.print();
            print_win.close();
        

        【讨论】:

          【解决方案12】:

          我编写了一个插件来解决这种情况。我对那里的插件不满意,并着手制作更广泛/可配置的东西。

          https://github.com/jasonday/printThis

          【讨论】:

          • 非常感谢杰森的辛勤工作.....!!真的会在我的更多项目中使用。多么令人兴奋的插件人......无语......
          • 这个插件真的很不错,除了在 Android 上的移动浏览器(Edge、Chrome 和 Firefox)上,即使打印预览只显示 div,它也会打印整个页面。这是浏览器、Android 还是插件中的错误?
          • @Vincent 这是库代码的问题。它是去年出现的,不幸的是我没有时间专门解决这个问题,但我很可能会在接下来的 4-6 周内解决它。
          • 如果您能解决这个问题,那就太好了,但您可能会感兴趣的是,我转而尝试打印 iframe,但出现了同样的问题。尝试仅在 Android 上打印 iframe 最终仍会打印整个页面,因此也许知道这将有助于您调试插件。
          • @Vincent - 这真的很有趣,所以您使用 javascript 尝试在没有 printThis 的情况下打印 iframe,但您遇到了同样的问题?
          【解决方案13】:

          与最佳答案相同,以防您需要像我一样打印图像:

          如果您想打印图像:

          function printElem(elem)
              {
                  Popup(jQuery(elem).attr('src'));
              }
          
              function Popup(data) 
              {
                  var mywindow = window.open('', 'my div', 'height=400,width=600');
                  mywindow.document.write('<html><head><title>my div</title>');
                  mywindow.document.write('</head><body >');
                  mywindow.document.write('<img src="'+data+'" />');
                  mywindow.document.write('</body></html>');
          
                  mywindow.print();
                  mywindow.close();
          
                  return true;
              }
          

          【讨论】:

          • 您在弹出窗口中缺少load 事件。没有它,您将打印空白页,因为未加载图像。 => $(popup).load(function(){ popup.focus(); popup.print(); });
          【解决方案14】:

          虽然@BC 的答案是打印单页的最佳选择。

          但是要使用 ctrl+P 同时打印多页 A4 尺寸的页面,以下解决方案可能会有所帮助。

          @media print{
          html *{
              height:0px!important;
              width:0px !important;
              margin: 0px !important;
              padding: 0px !important;
              min-height: 0px !important;
              line-height: 0px !important;
              overflow: visible !important;
              visibility: hidden ;
          
          
          }
          
          
          /*assing myPagesClass to every div you want to print on single separate A4 page*/
          
           body .myPagesClass {
              z-index: 100 !important;
              visibility: visible !important;
              position: relative !important;
              display: block !important;
              background-color: lightgray !important;
              height: 297mm !important;
              width: 211mm !important;
              position: relative !important;
          
              padding: 0px;
              top: 0 !important;
              left: 0 !important;
              margin: 0 !important;
              orphans: 0!important;
              widows: 0!important;
              overflow: visible !important;
              page-break-after: always;
          
          }
          @page{
              size: A4;
              margin: 0mm ;
              orphans: 0!important;
              widows: 0!important;
          }}
          

          【讨论】:

            【解决方案15】:

            这是一个适用于 IE 和 Chrome 的 IFrame 解决方案:

            function printHTML(htmlString) {
                var newIframe = document.createElement('iframe');
                newIframe.width = '1px';
                newIframe.height = '1px';
                newIframe.src = 'about:blank';
            
                // for IE wait for the IFrame to load so we can access contentWindow.document.body
                newIframe.onload = function() {
                    var script_tag = newIframe.contentWindow.document.createElement("script");
                    script_tag.type = "text/javascript";
                    var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
                    script_tag.appendChild(script);
            
                    newIframe.contentWindow.document.body.innerHTML = htmlString;
                    newIframe.contentWindow.document.body.appendChild(script_tag);
            
                    // for chrome, a timeout for loading large amounts of content
                    setTimeout(function() {
                        newIframe.contentWindow.Print();
                        newIframe.contentWindow.document.body.removeChild(script_tag);
                        newIframe.parentElement.removeChild(newIframe);
                    }, 200);
                };
                document.body.appendChild(newIframe);
            }
            

            【讨论】:

              【解决方案16】:

              使用Jquery,只需使用这个函数:

              <script>
              function printContent(el){
              var restorepage = $('body').html();
              var printcontent = $('#' + el).clone();
              $('body').empty().html(printcontent);
              window.print();
              $('body').html(restorepage);
              }
              </script>
              

              您的打印按钮将如下所示:

              <button id="print" onclick="printContent('id name of your div');" >Print</button>
              

              编辑:如果您确实有需要保留的表单数据,克隆不会复制它,因此您只需要获取所有表单数据并在还原后将其替换为:

              <script>
              function printContent(el){
              var restorepage = $('body').html();
              var printcontent = $('#' + el).clone();
              var enteredtext = $('#text').val();
              $('body').empty().html(printcontent);
              window.print();
              $('body').html(restorepage);
              $('#text').html(enteredtext);
              }
              </script>
              <textarea id="text"></textarea>
              

              【讨论】:

              • $('body').html(restorepage);将不起作用,因为当时没有可用的 body 元素。因此最好将其替换为 location.reload();
              • 没有。如果您重新加载页面,您将删除表单中的任何信息,或可能需要存在的任何其他设置。它工作得很好。如果您花时间查看代码,您会看到 var restorepage 确实具有可用于进行替换的所有页面信息。停止尝试编辑我的代码并自己测试它或了解函数的每个部分的作用。
              • 这样更好。它包括打印时的页面设计,不像上面提到的那样,我仍然需要从标题等中放置 css 链接。谢谢!
              • 你通过el 的方式很糟糕,尤其是在使用jQ 之后。最好简单地通过selector 并摆脱硬编码的#
              • 我今天一直使用这种方法,我注意到它在安卓设备(谷歌浏览器)上无法正常工作。页面的可打印区域每次都会更改,并且包含el 之外的一些额外部分。我认为打印命令是在恢复正文时发送的。
              【解决方案17】:

              我认为目前提出的解决方案有以下缺点:

              1. CSS 媒体查询解决方案假定只有一个 div 可打印。
              2. javascript 解决方案仅适用于某些浏览器。
              3. 破坏父窗口内容并重新创建会造成混乱。

              我对上述解决方案进行了改进。这是我已经测试过的东西,它具有以下好处。

              1. 适用于所有浏览器,包括 IE、Chrome、Safari 和 firefox。
              2. 不破坏和重新加载父窗口。
              3. 可以在一页上打印任意数量的 DIV。
              4. 使用 HTML 模板来避免容易出错的字符串连接。

              注意事项:

              1. 必须在新创建的窗口上有一个 onload="window.print()"。
              2. 不要从父级调用 targetwindow.close() 或 targetwindow.print()。
              3. 确保执行 targetwindow.document.close() 和 target.focus()
              4. 我使用的是 jquery,但您也可以使用纯 javascript 执行相同的技术。
              5. 您可以在此处https://math.tools/table/multiplication 看到这一点。您可以通过单击框标题上的打印按钮单独打印每个表格。

              <script id="print-header" type="text/x-jquery-tmpl">
                 <html>
                 <header>
                     <title>Printing Para {num}</title>
                     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
                     <style>
                        body {
                          max-width: 300px;
                        }
                     </style>
                 </header>
                 <body onload="window.print()">
                 <h2>Printing Para {num} </h2>
                 <h4>https://math.tools</h4>
              </script>
              <script id="print-footer" type="text/x-jquery-tmpl">
                  </body>
                  </html>
              </script>
              <script>
              $('.printthis').click(function() {
                 num = $(this).attr("data-id");
                 w = window.open();
                 w.document.write(
                                 $("#print-header").html().replace("{num}",num)  +
                                 $("#para-" + num).html() +
                                 $("#print-footer").html() 
                                 );
                 w.document.close();
                 w.focus();
                 //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window.
                 ///w.close(); Don't do this otherwise chrome won't work
              });
              </script>
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
              
              <a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>
              <a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>
                
              <p class="para" id="para-1">
                Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                
              
              <p class="para" id="para-2">
                Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                

              【讨论】:

              • 这非常好,而且跨浏览器的效果比公认的结果好得多!
              【解决方案18】:

              我使用Bill Paetzke 回答打印包含图像的 div,但它不适用于谷歌浏览器

              我只需要添加这一行 myWindow.onload=function(){ 即可使其工作,这是完整的代码

              <html>
              <head>
                  <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
                  <script type="text/javascript">
                      function PrintElem(elem) {
                          Popup($(elem).html());
                      }
              
                      function Popup(data) {
                          var myWindow = window.open('', 'my div', 'height=400,width=600');
                          myWindow.document.write('<html><head><title>my div</title>');
                          /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
                          myWindow.document.write('</head><body >');
                          myWindow.document.write(data);
                          myWindow.document.write('</body></html>');
                          myWindow.document.close(); // necessary for IE >= 10
              
                          myWindow.onload=function(){ // necessary if the div contain images
              
                              myWindow.focus(); // necessary for IE >= 10
                              myWindow.print();
                              myWindow.close();
                          };
                      }
                  </script>
              </head>
              <body>
                  <div id="myDiv">
                      This will be printed.
                      <img src="image.jpg"/>
                  </div>
                  <div>
                      This will not be printed.
                  </div>
                  <div id="anotherDiv">
                      Nor will this.
                  </div>
                  <input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
              </body>
              </html>
              

              如果有人只需要打印一个带有 id 的 div,他就不需要加载 jquery

              这是执行此操作的纯 JavaScript 代码

              <html>
              <head>
                  <script type="text/javascript">
                      function PrintDiv(id) {
                          var data=document.getElementById(id).innerHTML;
                          var myWindow = window.open('', 'my div', 'height=400,width=600');
                          myWindow.document.write('<html><head><title>my div</title>');
                          /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
                          myWindow.document.write('</head><body >');
                          myWindow.document.write(data);
                          myWindow.document.write('</body></html>');
                          myWindow.document.close(); // necessary for IE >= 10
              
                          myWindow.onload=function(){ // necessary if the div contain images
              
                              myWindow.focus(); // necessary for IE >= 10
                              myWindow.print();
                              myWindow.close();
                          };
                      }
                  </script>
              </head>
              <body>
                  <div id="myDiv">
                      This will be printed.
                      <img src="image.jpg"/>
                  </div>
                  <div>
                      This will not be printed.
                  </div>
                  <div id="anotherDiv">
                      Nor will this.
                  </div>
                  <input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
              </body>
              </html>
              

              我希望这可以帮助某人

              【讨论】:

              • 这对我有用!虽然原始答案使用“mywindow”与“myWindow”,但骆驼确实咬了我。谢谢!
              • @Robert: 先生,我得到的 myWindow 行中无法读取 null 的属性文档?
              • @KapilSoni 会打开新窗口吗?
              • @Robert- 不,先生没有重定向到新窗口,但我收到了 null ..你能告诉我为什么我返回 null 吗?
              • 我认为浏览器阻止了打开新窗口,您可以检查是否可以授予网站打开新窗口的权限?
              【解决方案19】:

              创建了可用于任何 HTML 元素的通用内容

              HTMLElement.prototype.printMe = printMe;
              function printMe(query){             
                   var myframe = document.createElement('IFRAME');
                   myframe.domain = document.domain;
                   myframe.style.position = "absolute";
                   myframe.style.top = "-10000px";
                   document.body.appendChild(myframe);
                   myframe.contentDocument.write(this.innerHTML) ;
                   setTimeout(function(){
                      myframe.focus();
                      myframe.contentWindow.print();
                      myframe.parentNode.removeChild(myframe) ;// remove frame
                   },3000); // wait for images to load inside iframe
                   window.focus();
              }
              //usage
              document.getElementById('xyz').printMe();
              document.getElementsByClassName('xyz')[0].printMe();
              

              希望这会有所帮助。

              【讨论】:

                【解决方案20】:

                接受的解决方案不起作用。 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;
                    }
                

                【讨论】:

                  【解决方案21】:

                  我修改了@BillPaetski 答案以使用 querySelector、添加可选 CSS、删除强制 H1 标记并使标题可选地指定或从窗口中拉出。它也不再自动打印并暴露内部结构,因此可以在包装器功能或您喜欢的情况下切换它们。

                  仅有的两个私有变量是 tmpWindow 和 tmpDoc,虽然我相信 title、css 和 elem 访问可能会有所不同,但应该假设所有函数参数都是私有的。

                  代码:
                  function PrintElem(elem, title, css) {
                      var tmpWindow = window.open('', 'PRINT', 'height=400,width=600');
                      var tmpDoc = tmpWindow.document;
                  
                      title = title || document.title;
                      css = css || "";
                  
                      this.setTitle = function(newTitle) {
                          title = newTitle || document.title;
                      };
                  
                      this.setCSS = function(newCSS) {
                          css = newCSS || "";
                      };
                  
                      this.basicHtml5 = function(innerHTML) {
                          return '<!doctype html><html>'+(innerHTML || "")+'</html>';
                      };
                  
                      this.htmlHead = function(innerHTML) {
                          return '<head>'+(innerHTML || "")+'</head>';
                      };
                  
                      this.htmlTitle = function(title) {
                          return '<title>'+(title || "")+'</title>';
                      };
                  
                      this.styleTag = function(innerHTML) {
                          return '<style>'+(innerHTML || "")+'</style>';
                      };
                  
                      this.htmlBody = function(innerHTML) {
                          return '<body>'+(innerHTML || "")+'</body>';
                      };
                  
                      this.build = function() {
                          tmpDoc.write(
                              this.basicHtml5(
                                  this.htmlHead(
                                      this.htmlTitle(title) + this.styleTag(css)
                                  ) + this.htmlBody(
                                      document.querySelector(elem).innerHTML
                                  )
                              )
                          );
                          tmpDoc.close(); // necessary for IE >= 10
                      };
                  
                      this.print = function() {
                          tmpWindow.focus(); // necessary for IE >= 10*/
                          tmpWindow.print();
                          tmpWindow.close();
                      };
                  
                      this.build();
                      return this;
                  }
                  
                  用法:
                  DOMPrinter = PrintElem('#app-container');
                  DOMPrinter.print();
                  

                  【讨论】:

                  • 此外,它不会复制 &lt;input&gt; 元素的值。我如何使用它,包括用户输入的内容?
                  • @Malky.Kid 请想想你在问什么。如果要打印表单,需要在表单元素上钩住模糊事件,并将&lt;input&gt;&lt;select&gt;&lt;textarea&gt;组件的属性值、selected、default和innerText设置为它们的运行时值。有替代方案,但这不是这个脚本的问题,而是浏览器工作方式的问题,并通过输入、画布等获取文档的innerHTML 属性。
                  • 我已经通过.attr('value',) 找到了解决方案。我什至已经为 textarea(通过附加)和复选框(.attr('checked',))完成了它。我抱歉如果我没有充分考虑我的问题。
                  • 想与全班分享?可能是 cmets 中的要点或其他内容。我会赞成的。
                  【解决方案22】:

                  注意:这仅适用于启用 jQuery 的网站

                  这个很酷的技巧非常简单。它在 Google Chrome 浏览器中对我有用。 Firefox 不允许您在没有插件的情况下打印为 PDF。

                  1. 首先,使用 (Ctrl + Shift + I) / (Cmd + Option + I) 打开检查器。
                  2. 在控制台中输入此代码:

                  var jqchild = document.createElement('script');
                  jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
                  document.getElementsByTagName('body')[0].appendChild(jqchild);
                  $("#myDivWithStyles").print(); // Replace ID with yours
                  
                  1. 它启动打印对话框。进行物理打印或将其保存为 PDF(在 chrome 中)。完成!

                  逻辑很简单。我们正在创建一个新的脚本标签并将其附加到结束正文标签的前面。我们在 HTML 中注入了一个 jQuery 打印扩展。用您自己的 Div 标签 ID 更改 myDivWithStyles。现在它负责准备一个可打印的虚拟窗口。

                  在任何网站上试用。唯一需要注意的是,有时复杂的 CSS 会导致样式丢失。但我们大多数时候都能得到内容。

                  【讨论】:

                    【解决方案23】:

                    如果您想拥有原始文档中的所有样式(包括内联样式),您可以使用这种方法。

                    1. 复制完整的文档
                    2. 将正文替换为您要打印的元素。

                    实施:

                    class PrintUtil {
                      static printDiv(elementId) {
                        let printElement = document.getElementById(elementId);
                        var printWindow = window.open('', 'PRINT');
                        printWindow.document.write(document.documentElement.innerHTML);
                        setTimeout(() => { // Needed for large documents
                          printWindow.document.body.style.margin = '0 0';
                          printWindow.document.body.innerHTML = printElement.outerHTML;
                          printWindow.document.close(); // necessary for IE >= 10
                          printWindow.focus(); // necessary for IE >= 10*/
                          printWindow.print();
                          printWindow.close();
                        }, 1000)
                      }   
                    }
                    

                    【讨论】:

                    • 我不知道这是最好的解决方案,但效果很好。谢谢!
                    【解决方案24】:

                    下面的代码复制了查询选择器所针对的所有相关节点,复制了它们在屏幕上看到的样式,因为用于定位 css 选择器的许多父元素将丢失。如果子节点有很多样式,这会导致一些延迟。

                    理想情况下,您应该准备好打印样式表,但这适用于没有要插入的打印样式表并且您希望按照屏幕上显示的方式打印的用例。

                    如果您在此页面的浏览器控制台中复制以下项目,它将打印此页面上的所有代码sn-ps。

                    +function() {
                        /**
                         * copied from  https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
                         * @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
                         */
                        var copyComputedStyle = function(from,to){
                            var computed_style_object = false;
                            //trying to figure out which style object we need to use depense on the browser support
                            //so we try until we have one
                            computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);
                    
                            //if the browser dose not support both methods we will return null
                            if(!computed_style_object) return null;
                    
                                var stylePropertyValid = function(name,value){
                                            //checking that the value is not a undefined
                                    return typeof value !== 'undefined' &&
                                            //checking that the value is not a object
                                            typeof value !== 'object' &&
                                            //checking that the value is not a function
                                            typeof value !== 'function' &&
                                            //checking that we dosent have empty string
                                            value.length > 0 &&
                                            //checking that the property is not int index ( happens on some browser
                                            value != parseInt(value)
                    
                                };
                    
                            //we iterating the computed style object and compy the style props and the values
                            for(property in computed_style_object)
                            {
                                //checking if the property and value we get are valid sinse browser have different implementations
                                    if(stylePropertyValid(property,computed_style_object[property]))
                                    {
                                        //applying the style property to the target element
                                            to.style[property] = computed_style_object[property];
                    
                                    }   
                            }   
                    
                        };
                    
                    
                        // Copy over all relevant styles to preserve styling, work the way down the children tree.
                        var buildChild = function(masterList, childList) {
                            for(c=0; c<masterList.length; c++) {
                               var master = masterList[c];
                               var child = childList[c];
                               copyComputedStyle(master, child);
                               if(master.children && master.children.length > 0) {
                                   buildChild(master.children, child.children);
                               }
                            }
                        }
                    
                        /** select elements to print with query selector **/
                        var printSelection = function(querySelector) {
                            // Create an iframe to make sure everything is clean and ordered.
                            var iframe = document.createElement('iframe');
                            // Give it enough dimension so you can visually check when modifying.
                            iframe.width = document.width;
                            iframe.height = document.height;
                            // Add it to the current document to be sure it has the internal objects set up.
                            document.body.append(iframe);
                    
                            var nodes = document.querySelectorAll(querySelector);
                            if(!nodes || nodes.length == 0) {
                               console.error('Printing Faillure: Nothing to print. Please check your querySelector');
                               return;
                            }
                    
                            for(i=0; i < nodes.length; i++) {
                    
                                // Get the node you wish to print.
                                var origNode = nodes[i];
                    
                                // Clone it and all it's children
                                var node = origNode.cloneNode(true);
                    
                                // Copy the base style.
                                copyComputedStyle(origNode, node);
                    
                                if(origNode.children && origNode.children.length > 0) {
                                    buildChild(origNode.children, node.children);
                                }
                    
                                // Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.
                    
                                iframe.contentWindow.document.body.append(node);
                            }
                            // Print the window
                            iframe.contentWindow.print();
                    
                            // Give the browser a second to gather the data then remove the iframe.
                            window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
                        }
                    window.printSelection = printSelection;
                    }();
                    printSelection('.default.prettyprint.prettyprinted')
                    

                    【讨论】:

                      【解决方案25】:

                      这是一个非常老的帖子,但这是我使用正确答案所做的更新。我的解决方案也使用 jQuery。

                      重点是使用正确的打印视图,包括所有样式表以实现正确的格式设置,并且在大多数浏览器中都得到支持。

                      function PrintElem(elem, title, offset)
                      {
                          // Title constructor
                          title = title || $('title').text();
                          // Offset for the print
                          offset = offset || 0;
                      
                          // Loading start
                          var dStart = Math.round(new Date().getTime()/1000),
                              $html = $('html');
                              i = 0;
                      
                          // Start building HTML
                          var HTML = '<html';
                      
                          if(typeof ($html.attr('lang')) !== 'undefined') {
                              HTML+=' lang=' + $html.attr('lang');
                          }
                      
                          if(typeof ($html.attr('id')) !== 'undefined') {
                              HTML+=' id=' + $html.attr('id');
                          }
                      
                          if(typeof ($html.attr('xmlns')) !== 'undefined') {
                              HTML+=' xmlns=' + $html.attr('xmlns');
                          }
                      
                          // Close HTML and start build HEAD
                          HTML+='><head>';
                      
                          // Get all meta tags
                          $('head > meta').each(function(){
                              var $this = $(this),
                                  $meta = '<meta';
                      
                              if(typeof ($this.attr('charset')) !== 'undefined') {
                                  $meta+=' charset=' + $this.attr('charset');
                              }
                      
                              if(typeof ($this.attr('name')) !== 'undefined') {
                                  $meta+=' name=' + $this.attr('name');
                              }
                      
                              if(typeof ($this.attr('http-equiv')) !== 'undefined') {
                                  $meta+=' http-equiv=' + $this.attr('http-equiv');
                              }
                      
                              if(typeof ($this.attr('content')) !== 'undefined') {
                                  $meta+=' content=' + $this.attr('content');
                              }
                      
                              $meta+=' />';
                      
                              HTML+= $meta;
                              i++;
                      
                          }).promise().done(function(){
                      
                              // Insert title
                              HTML+= '<title>' + title  + '</title>';
                      
                              // Let's pickup all CSS files for the formatting
                              $('head > link[rel="stylesheet"]').each(function(){
                                  HTML+= '<link rel="stylesheet" href="' + $(this).attr('href') + '" />';
                                  i++;
                              }).promise().done(function(){
                                  // Print setup
                                  HTML+= '<style>body{display:none;}@media print{body{display:block;}}</style>';
                      
                                  // Finish HTML
                                  HTML+= '</head><body>';
                                  HTML+= '<h1 class="text-center mb-3">' + title  + '</h1>';
                                  HTML+= elem.html();
                                  HTML+= '</body></html>';
                      
                                  // Open new window
                                  var printWindow = window.open('', 'PRINT', 'height=' + $(window).height() + ',width=' + $(window).width());
                                  // Append new window HTML
                                  printWindow.document.write(HTML);
                      
                                  printWindow.document.close(); // necessary for IE >= 10
                                  printWindow.focus(); // necessary for IE >= 10*/
                      console.log(printWindow.document);
                                  /* Make sure that page is loaded correctly */
                                  $(printWindow).on('load', function(){                   
                                      setTimeout(function(){
                                          // Open print
                                          printWindow.print();
                      
                                          // Close on print
                                          setTimeout(function(){
                                              printWindow.close();
                                              return true;
                                          }, 3);
                      
                                      }, (Math.round(new Date().getTime()/1000) - dStart)+i+offset);
                                  });
                              });
                          });
                      }
                      

                      稍后你需要这样的东西:

                      $(document).on('click', '.some-print', function() {
                          PrintElem($(this), 'My Print Title');
                          return false;
                      });
                      

                      试试看。

                      【讨论】:

                        【解决方案26】:

                        只需使用PrintJS

                        let printjs = document.createElement("script");
                        printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
                        document.body.appendChild(printjs);
                        
                        printjs.onload = function (){
                            printJS('id_of_div_you_want_to_print', 'html');
                        }
                        

                        【讨论】:

                          【解决方案27】:

                          这应该可行:

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

                          【讨论】:

                            【解决方案28】:

                            虽然有点晚了,但我发现这真的很好!!!

                            function printDiv(divID) {
                                //Get the HTML of div
                                var divElements = document.getElementById(divID).innerHTML;
                                //Get the HTML of whole page
                                var oldPage = document.body.innerHTML;
                            
                                //Reset the page's HTML with div's HTML only
                                document.body.innerHTML = 
                                   "<html><head><title></title></head><body>" + 
                                          divElements + "</body>";
                            
                                //Print Page
                                window.print();
                            
                                //Restore orignal HTML
                                document.body.innerHTML = oldPage;
                                      
                            }
                            

                            【讨论】:

                            • 在使用 Vue 或 React 等框架时,您可能会遇到一个问题,即当您从打印屏幕返回时,您的 DOM 会失去反应性。
                            • 你总是可以建议新方法@JamesStewart
                            【解决方案29】:

                            HTML > 头部

                              <script type="text/javascript">
                                function printDiv() {
                                    var divToPrint = document.getElementById('printArea');  
                                //Firefox was just opening a new window with same content as opener and not performing the printing dialog, so needed to make it open a new instance of the window opener    
                                    newWin= window.open(self.location.href);
                                //We want to format the document appropriately
                                   newWin.document.write("\<!DOCTYPE html\>\<html lang='es'\>\<head\>\<meta charset='utf-8'\/\>\<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'\>\<meta name='HandheldFriendly' content='true'\/\>");
                                //HTML ELEMENTS THAT WE WANT TO HIDE FROM THE PRINTING AREA
                                    newWin.document.write("<style type='text/css'>@media print{.dataTables_info,.dataTables_filter{height:0!important;width:0!important;margin:0!important;padding:0!important;min-height:0!important;line-height:0!important;overflow:visible!important;visibility:hidden}");
                                //General Styling for Printing
                                    newWin.document.write("body {z-index:100!important;visibility:visible!important;position:relative!important;display:block!important;background-color:lightgray!important;height:297mm!important;width:211mm!important;position:relative!important;padding:0;top:0!important;left:0!important;margin:0!important;orphans:0!important;widows:0!important;overflow:visible!important;page-break-after:always}");
                                //Some forced styling in css rules includying page break for a div
                                    newWin.document.write("body h1{font-size:1em; font-family:Verdana;} a.marked{color:black; text-decoration:none} .pagebreak { page-break-before: always; } ");
                                    newWin.document.write("@page{size:A4; margin:2em; orphans:0!important;widows:0!important}}</style>\<\/head>\<body>");
                                    newWin.document.write(divToPrint.innerHTML);
                                    newWin.document.write("</body></html>");
                                    newWin.focus();
                                    newWin.print();
                                }
                                </script>
                            

                            HTML > 正文

                            <div id="printArea">
                            
                            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                            <!-- Page break -->
                            <div class="pagebreak">&nbsp;</div>
                            
                            It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
                            </div>
                            

                            【讨论】:

                              猜你喜欢
                              • 2021-09-13
                              • 1970-01-01
                              • 1970-01-01
                              • 2022-01-25
                              相关资源
                              最近更新 更多