【问题标题】:Print specific part of webpage打印网页的特定部分
【发布时间】:2012-10-11 10:02:15
【问题描述】:

我正在尝试打印我的应用程序的特定部分。

应用程序有一个用户列表,显示他们的名字和姓氏。当我单击用户时,我会弹出一个包含有关他们的更详细信息的弹出窗口。

我将如何只为我单击的用户打印弹出窗口? 弹出窗口如下所示:

 <div id="user<?=$user->id;?>" class="popup">
      <div class="details">
           User details...
      </div>
      <a href="#print">Print</a>
 </div>

打印按钮还没有工作。

【问题讨论】:

标签: javascript html printing


【解决方案1】:

您必须打开一个新窗口(或导航到一个新页面),其中只包含您希望用户能够打印的信息

JavaScript:

function printInfo(ele) {
    var openWindow = window.open("", "title", "attributes");
    openWindow.document.write(ele.previousSibling.innerHTML);
    openWindow.document.close();
    openWindow.focus();
    openWindow.print();
    openWindow.close();
}

HTML:

<div id="....">
    <div>
        content to print
    </div><a href="#" onclick="printInfo(this)">Print</a>
</div>

这里有几点注意事项:锚点和包含要打印的内容的 div 之间不能有空格

【讨论】:

  • 这太棒了!当然,如果您不想在您的项目之后添加打印链接,或者您希望它更漂亮一点,那么您将面临一些挑战。我通过为 href 提供一个 ID、将 Print 更改为非中断空间并使用 getElementById 在其他地方引用 click() 事件来解决了这个挑战。谢谢!!
  • 啊,在尝试了 angular/typescript 中的一万亿个 html 到 pdf 解决方案之后,终于成功了
【解决方案2】:

您可以使用简单的 JavaScript 从页面打印特定的 div。

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

【讨论】:

  • 如果您使用此代码打印的 div 需要任何 CSS 以您想要的方式呈现,请小心。如果是这样,您必须确保使用WinPrint.document.write(cssLinkTag) 将其添加到页面中。
  • 如果我想改变方向怎么办?
  • 当div中包含从服务器端获取的数据时,打印div不起作用:stackoverflow.com/questions/34206638/…
  • 基于此答案的小提琴:jsfiddle.net/jdavidzapatab/6sctvg2z
  • @WallyLawless 能否提供一个示例来说明如何派生 css 标签?
【解决方案3】:

在这里回答:https://stackoverflow.com/a/1072151/421243,您可以使用 Javascript 将特定部分添加到隐藏框架中,将其聚焦并打印出来。

【讨论】:

  • 那是用javascript
【解决方案4】:

printPageArea() 函数中,传递您要打印的特定div ID。我从 codexworld.com 找到了这段 JavaScript 代码。

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint = window.open('', '', 'width=900,height=650');
    WinPrint.document.write(printContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

完整的代码和教程可以从这里找到 - How to Print Page Area using JavaScript

【讨论】:

    【解决方案5】:

    我制作了这个 jQuery 扩展来打印所选元素的 HTML:$('#div2').print();

    $.fn.extend({
        print: function() {
            var frameName = 'printIframe';
            var doc = window.frames[frameName];
            if (!doc) {
                $('<iframe>').hide().attr('name', frameName).appendTo(document.body);
                doc = window.frames[frameName];
            }
            doc.document.body.innerHTML = this.html();
            doc.window.print();
            return this;
        }
    });
    

    看到它在行动here

    【讨论】:

    • 不适用于 Chrome。此外,您应该尝试在答案中发布您的代码。
    • 我认为,作为一个社区,我们实际上可以尝试通过评论和复制该死的代码超过我们自己 v_v 不要指望每个人都对 StackOverflow 礼仪的复杂性如此熟悉......
    • 谢谢,为什么css文件不能添加?
    【解决方案6】:

    您实际上可以使用简单的CSS 来代替所有复杂的 JavaScript,而实现这一点:只需使用两个 CSS 文件,一个用于您的正常屏幕显示,另一个用于显示 ONLY 内容你想打印。在后一个文件中,隐藏您不想打印的所有内容,仅显示弹出窗口。

    记得定义两个 CSS 文件的 media 属性:

    <link rel="stylesheet" href="screen-css.css" media="all" />
    <link rel="stylesheet" href="print-css.css" media="print" />
    

    【讨论】:

    • 我制作了复杂的 JavaScript,因为我有更多的 1 个按钮来选择要打印的区域。我使用 css "@media print {" 来隐藏按钮。
    【解决方案7】:

    这是我的增强版本,当我们要加载 css 文件或要打印的部分中有图像参考时。

    在这些情况下,我们必须等到 css 文件或图像完全加载后才能调用 print() 函数。因此,我们最好将 print() 和 close() 函数调用移动到 html 中。以下是代码示例:

    var prtContent = document.getElementById("order-to-print");
    var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
    WinPrint.document.write('<html><head>');
    WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/normalize.css">');
    WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/receipt.css">');
    WinPrint.document.write('</head><body onload="print();close();">');
    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.write('</body></html>');
    WinPrint.document.close();
    WinPrint.focus();
    

    【讨论】:

      【解决方案8】:

      只需使用 CSS 来隐藏您不想打印的内容。 当用户选择打印时 - 页面将查看“media="print" CSS 以获取有关页面布局的说明。

      media="print" CSS 包含隐藏我们不想打印的内容的说明。

      <!-- CSS for the things we want to print (print view) -->
      <style type="text/css" media="print">
      
      #SCREEN_VIEW_CONTAINER{
              display: none;
          }
      .other_print_layout{
              background-color:#FFF;
          }
      </style>
      
      <!-- CSS for the things we DO NOT want to print (web view) -->
      <style type="text/css" media="screen">
      
         #PRINT_VIEW{
            display: none;
         }
      .other_web_layout{
              background-color:#E0E0E0;
          }
      </style>
      

      <div id="SCREEN_VIEW_CONTAINER">
           the stuff I DO NOT want printed is here and will be hidden - 
           and not printed when the user selects print.
      </div>
      
      <div id="PRINT_VIEW">
           the stuff I DO want printed is here.
      </div>
      

      【讨论】:

      • 这很好用——而且非常简单明了——谢谢! :)
      【解决方案9】:

      我有更好的选择,

      先按类名或id分隔可打印和不可打印部分

      window.onafterprint = onAfterPrint;
      
      function print(){
        //hide the nonPrintable div  
      }
      
      function onAfterPrint(){
        // Visible the nonPrintable div
      }
      &lt;input type="button" onclick="print()" value="Print"/&gt;

      就是这样

      【讨论】:

      • 我不会说更好,你应该明确地分享一个小例子。但这看起来是一种非常好的方法。例如,可能有一个 .printable 类。但是,这会弄乱 CSS(例如固定位置)。
      【解决方案10】:

      我编写了一个名为 PrintElements 的小型 JavaScript 模块,用于动态打印网页的某些部分。

      它通过迭代选定的节点元素来工作,对于每个节点,它会向上遍历 DOM 树直到 BODY 元素。在每个级别,包括初始级别(即要打印的节点的级别),它都将标记类(pe-preserve-print)附加到当前节点。然后将另一个标记类 (pe-no-print) 附加到当前节点的所有兄弟姐妹,但前提是它们上没有 pe-preserve-print 类。作为第三幕,它还将另一个类附加到保留的祖先元素pe-preserve-ancestor

      一个非常简单的补充打印 CSS 将隐藏和显示相应的元素。这种方法的一些好处是保留了所有样式,它不会打开新窗口,不需要移动大量 DOM 元素,而且通常不会侵入您的原始文档。

      demo,或阅读相关文章for further details

      【讨论】:

      • 对我不起作用。印刷垃圾。我试图打印一个弹出窗口。
      【解决方案11】:

      试试这个很棒的 ink-html

      import print from 'ink-html'
      // const print = require('ink-html').default
      
      // js
      print(window.querySelector('#printable'))
      // Vue.js
      print(this.$refs.printable.$el)
      

      【讨论】:

        【解决方案12】:

        样式

         @media print {
        
               .no-print{
                       display : none !important;
                        }
                      }
        

        jQuery

            function printInvoice()
         {
             printDiv = "#printDiv"; // id of the div you want to print
             $("*").addClass("no-print");
             $(printDiv+" *").removeClass("no-print");
             $(printDiv).removeClass("no-print");
        
             parent =  $(printDiv).parent();
             while($(parent).length)
             {
                 $(parent).removeClass("no-print");
                 parent =  $(parent).parent();
             }
             window.print();
        
         }
        

        打印按钮 Html

        <input type="button" onclick="printInvoice();" value="Print">
        

        【讨论】:

          【解决方案13】:

          这对我有用

          使用 jQuery 和 https://developer.mozilla.org/en-US/docs/Web/API/Window/open

            var $linkToOpenPrintDialog = $('#tvcPrintThisLinkId');
            var windowObjectReference = null;
            var windowFeatures = 'left=0,top=0,width=800,height=900,menubar=no,toolbar=no,location=yes,resizable=no,scrollbars=no,status=no';
            var windowFeaturesStyles = '<link rel="stylesheet" media="print" href="/wp-content/themes/salient-child/dist/css/app-print.css">';
          
            $linkToOpenPrintDialog.on('click', function(event) {
              openPrintDialog(this.href, this.target, 'tvcInnerCalculatorDivId', event);    
              return false;
            });
          
            function openPrintDialog(url, windowName, elementToOpen, event) {
          
              var elementContent = document.getElementById(elementToOpen);
          
              if(windowObjectReference == null || windowObjectReference.closed) {
          
                windowObjectReference = window.open( url, windowName, windowFeatures);
                windowObjectReference.document.write(windowFeaturesStyles);
                windowObjectReference.document.write(elementContent.innerHTML);
                windowObjectReference.document.close();
                windowObjectReference.focus();
                windowObjectReference.print();
                windowObjectReference.close();
          
              } else {
                windowObjectReference.focus();
              };
          
              event.preventDefault();
            }
          

          app-print.css

          @media print { 
          
            body { 
              margin: 0; 
              color: black; 
              background-color: white;
            } 
          
          }
          

          【讨论】:

            【解决方案14】:

            试试这个:

            1. 将容器的 innerHTML 转储到 iFrame(以及任何特定于打印的 CSS
            2. 打印 iFrame 内容。

            JSFiddle 中试用(iframe 在 StackOverflow 的预览中似乎不起作用)

            您可以在此处查看代码,但由于 StackOverflow 渲染器中可能存在的安全限制,它无法运行。

            const printButton = document.getElementById('print-button');
            
            printButton.addEventListener('click', event => {
              // build the new HTML page
              const content = document.getElementById('name-card').innerHTML;
              const printHtml = `<html>
                  <head>
                      <meta charset="utf-8">
                      <title>Name Card</title>
                  </head>
                  <body>${content}</body>
              </html>`;
                  
              // get the iframe
              let iFrame = document.getElementById('print-iframe');
              
              // set the iFrame contents and print
              iFrame.contentDocument.body.innerHTML = printHtml;
              iFrame.focus();
                iFrame.contentWindow.print();
              
            });
            <h1>Print your name badge</h1>
            <div id="name-card" class="card">
              <p>Hello my name is</p>
              <h2>Max Powers</h2>
            </div>
            <p>You will be required to wear your name badge at all times</p>
            <a id="print-button" class="btn btn-primary">Print</a>
            
            <iframe id="print-iframe" width="0" height="0"></iframe>

            【讨论】:

              【解决方案15】:

              试试这个。

              export function printSectionOfWebpage(sectionSelector) {
                  const $body = jquery('body');
                  const $sectionToPrint = jquery(sectionSelector);
                  const $sectionToPrintParent = $sectionToPrint.parent();
                  const $printContainer = jquery('<div style="position:relative;">');
              
                  $printContainer.height($sectionToPrint.height()).append($sectionToPrint).prependTo($body);
              
                  const $content = $body.children().not($printContainer).not('script').detach();
              
                  /**
                   * Needed for those who use Bootstrap 3.x, because some of
                   * its `@media print` styles ain't play nicely when printing.
                   */
                  const $patchedStyle = jquery('<style media="print">')
                      .text(
                          `
                        img { max-width: none !important; }
                        a[href]:after { content: ""; }
                      `
                      )
                      .appendTo('head');
              
                  window.print();
              
                  $body.prepend($content);
                  $sectionToPrintParent.prepend($sectionToPrint);
              
                  $printContainer.remove();
                  $patchedStyle.remove();
              }
              

              【讨论】:

              • 请解释您的代码。这将有助于其他人了解您的所作所为。
              【解决方案16】:

              你可以用这个JQuery plugin

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-11-07
              • 2014-02-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多