Reputation: 4372
I am building a web app that needs to print a report when the user clicks a button. None of the content in the report is visible on the page, it only gets created when the user clicks the button. My initial idea was to simply open a new window, set the content, and then close the window after printing. However this is not an option because the users are using a browser in kiosk mode that is incapable of opening new tabs/windows. The requirement is that the report needs to print without redirecting from the current page. Only the report itself should be printed, none of the content from the current page can be included.
I understand that this has been posted here multiple times, but I have looked at a lot of those posts which is how I got as far as I am now.
When I click the button and print the page, it prints a blank page. I have no idea why this isn't working.
Here is what I have so far
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("");
}
});
});
});
Upvotes: 3
Views: 4921
Reputation: 141
You can insert the printable content into a hidden div and use the @media print to unhide it.
.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>
Upvotes: 6