How to view the print preview of a specific div of the page and take a printout of that specific div only?
1.First, create a full-screen modal on the page:
<div class="modal fade" id="myModal"> <div class="modal-content"> <div class="modal-header text-center"> <button type="button" class="close hidden-print close-button col-md-push-11 col-sm-push-11 hidden-xs" data-toggle="toggle" data-placement="left" title="Close Print Preview" data-dismiss="modal">×</button> <h4 class="modal-title" id="modal-title"></h4> <div class="col-md-12" > <div class="col-md-5"></div> <button onclick="print()" data-toggle="toggle" data-placement="bottom" title="" data-original-title="Print" class="btn btn-success hidden-print col-md-1">Print</button> <button data-dismiss="modal" data-toggle="toggle" data-placement="bottom" title="" style="margin-left: 5px;" data-original-title="Close Print Preview " class="btn btn-danger hidden-print col-md-1">Close</button> <div class="col-md-5"></div> </div> </div> <div class="modal-body" id="modal-body"> </div> </div> </div>
2. Add these style to your CSS file:
@media print { .modal, .modal * { overflow: visible !important;} .modal { position: absolute !important; left: 0 !important; top: 0 !important;} } .close-button { opacity:1; font-size: 36px; color:red; position:fixed; margin-left: 4%; z-index: 9; }
3. Create following Javascript function in your js file:
/ item-> is a string that can be used to show on the title of print preview.
// div-> is the id of that div whose data we want to print or want to seen print preview of which div:
function print_history(item,div) {
$("#myModal").modal("show");
$('.container-fluid').hide(); //container-fluid- this class is used in the top level div of the page and used to hide all the data of the page.
document.getElementById('modal-title').innerHTML = “ Print Preview";
document.getElementById('modal-body').innerHTML = $('#'+div).html();
$("#myModal").on('show.bs.modal', function () {
document.getElementById('modal-body').innerHTML = $('#'+div).html();
$('.container-fluid').hide(); });
$("#myModal").on('hide.bs.modal', function () {
$('.container-fluid').show(); });
$("#myModal").on('hidden.bs.modal', function () {
document.getElementById('modal-body').innerHTML = ''; }); }
4. Now call print_history(item,div) function at on click event of any button and pass specific arguments.
It looks like in below snapshot: