2017-04-11 53 views
1

我建立一个Web应用程序需要当用户点击一个按钮,打印报告。报告中的内容在页面上都不显示,只在用户单击按钮时才会创建。我最初的想法是打开一个新窗口,设置内容,然后在打印后关闭窗口。但是,这不是一种选择,因为用户正在使用无法打开新选项卡/窗口的Kiosk模式的浏览器。要求是报告需要打印而不需要从当前页面重定向。只有报告本身应该打印,当前页面的内容都不能包含在内。使用CSS只打印隐藏的内容

据我所知,这已经张贴在这里多次,但我已经看了好多那些帖子的是我如何获得尽可能现在的我。

当我点击按钮,打印页面,将打印空白页。我不知道为什么这不起作用。

这里是我迄今为止

HTML

<html class="printable"> 
<head> 
    <link rel="stylesheet" type="text/css" href="css/print-style.css"> 
    <script src="js/jquery.js"></script> 
    <script src="js/report.js"></script> 
</head> 
<body class="printable"> 
    <div> 
     <h1>Content that shouldn't print</h1> 
     <h2>Content that shouldn't print</h2> 
     <h3>Content that shouldn't print</h3> 
     <h4>Content that shouldn't print</h4> 
    </div> 
    <div id="report" class="print-only"></div> 
</body> 
</html> 

CSS

@media print { 
    :not(.printable) { 
     display: none; 
    } 

    .print-only { 
     display: block; 
    } 
} 

.print-only { 
    display: none; 
} 

的JavaScript

$(function() { 
    $("#print-button").click(function() { 
     $.ajax({ 
      url: "get-report", 
      success: function(resp) { 
       $("#report").html(resp); // populate the report div with the response from the ajax call 
       $("#report").children("*").addClass("printable"); // make all children of the report div printable 
       window.print(); 
       $("#report").html(""); 
      } 
     }); 
    }); 

}); 

回答

2

您可以将打印内容到一个隐藏的div和使用@medi打印以取消隐藏。

.print {display:none;} 
 

 
@media print { 
 
    body :not(.both) {display:none;} 
 
    .print {display:block!important;} 
 
}
<html> 
 
<head></head> 
 
<body> 
 
    <div> 
 
    Screen content 
 
    </div> 
 
    
 
    <div class="both">Both media</div> 
 
    
 
    <div class="print"> 
 
    Printable content 
 
    </div> 
 
</body> 
 
</html>

+0

这就是我想要做的一切 – zero01alpha

+0

你插入绝版地块将在打印版本而已。我添加了一个示例代码,答案是你想要的还是我错过了什么? – Tal

+0

您的代码和我的唯一区别在于,我是黑名单,列出要在打印时隐藏的内容,并且您是白名单。此解决方案不适合我。 – zero01alpha