如何打印指定的div(无需手动禁用页面上的所有其他内容)?

我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。

该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。


当前回答

在我的例子中,我必须在页面中打印图像。当我使用投票的解决方案时,我有一个空白页面,另一个显示图像。希望它能帮助到一些人。

下面是我使用的css:

@media print {
  body * {
    visibility: hidden;
  }

  #not-print * {
    display: none;
  }

  #to-print, #to-print * {
    visibility: visible;
  }

  #to-print {
    display: block !important;
    position: absolute;
    left: 0;
    top: 0;
    width: auto;
    height: 99%;
  }
}

我的html是:

<div id="not-print" >
  <header class="row wrapper page-heading">

  </header>

  <div class="wrapper wrapper-content">
    <%= image_tag @qrcode.image_url,  size: "250x250" , alt: "#{@qrcode.name}" %>
  </div>
</div>

<div id="to-print" style="display: none;">
  <%= image_tag @qrcode.image_url,  size: "300x300" , alt: "#{@qrcode.name}" %>
</div>

其他回答

我拿起使用JavaScript的内容,并创建了一个窗口,我可以打印代替…

没有CSS小丑,html和纯javascript与iframe工作最好。然后只需点击文本,你想打印。带有文本内容的id元素的当前示例;

html的身体:

<div id="monitor" onclick="idElementPrint()">text i want to print</div>

纯javascript:

//or: monitor.textContent = "click me to print textual content";

const idElementPrint = () => {
    let ifram = document.createElement("iframe");
    ifram.style = "display:none";
    document.body.appendChild(ifram);
    pri = ifram.contentWindow;
    pri.document.open();
    pri.document.write(monitor.textContent);
    pri.document.close();
    pri.focus();
    pri.print();
    }
It's better solution. You can use it Angualr/React

Html

 <div class="row" id="printableId">
      Your html 
    </div>

Javascript

   function printPage(){
        
        var printHtml = window.open('', 'PRINT', 'height=400,width=600');
    
        printHtml.document.write('<html><head>');
        printHtml.document.write(document.getElementById("printableId").innerHTML);
        printHtml.document.write('</body></html>');
    
        printHtml.document.close(); 
        printHtml.focus(); = 10*/
    
        printHtml.print();
        printHtml.close();
    
        return true;
    
      }

到目前为止,所有的答案都是有缺陷的——它们要么涉及在所有内容中添加class="noprint",要么会在#printable中混乱显示。

我认为最好的解决方案是在不可打印的东西周围创建一个包装器:

<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
        #non-printable { display: none; }
        #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
        Your normal page contents
    </div>

    <div id="printable">
        Printer version
    </div>
</body>

当然,这并不是完美的,因为它涉及到在HTML中移动一些东西……

如果你只想打印这个div,你必须使用指令:

@media print{
    *{display:none;}
    #mydiv{display:block;}
}