Я пытаюсь иметь кнопку на разных Div. Когда вы нажимаете на соответствующую кнопку, она скрывает все остальные элементы, кроме того, который вы хотите распечатать. Все работает хорошо, за исключением того, что всегда печатает 2 лишних пустых страницы в конце. Я верю из-за видимости: скрыто, вещи все еще «там».
Ниже моя функция, CSS запрос и пример HTML, где button / div.
JS функция
function printThisTableDiv(tableID) {
// let printContents = document.getElementsByClassName(tableID);
let existingTags = document.querySelectorAll('.section-to-print-body');
let i;
for (i = 0; i < existingTags.length; i++) {
existingTags[i].classList.remove('section-to-print-body');
}
document.querySelector(tableID).classList.add("section-to-print-body");
window.print();
};
CSS
@media print {
/*set properties for the whole page, this prevents duplicate pages*/
html,
body {
height: 100vh;
margin: 0 !important;
padding: 0 !important;
overflow: visible;
color: black;
/*font-weight: bold;*/
}
/*set all HTML elements to hidden*/
body * {
visibility: hidden;
/*height: auto;*/
}
/*CSS classes to set chosen elements and all their children to visible*/
.section-to-print-head,
.section-to-print-body,
.section-to-print-head *,
.section-to-print-body * {
visibility: visible;
page-break-after: avoid !important;
}
.printThis {
color: black;
/*font-weight: bold;*/
}
/*POSITIONING OF HEAD*/
.section-to-print-head {
position: static;
left: 0;
top: 0;
width: 100%;
}
/*POSITIONING OF BODY*/
.section-to-print-body {
position: static;
top: 50px;
left: 0;
z-index: 999;
width: 100%;
height: 99%;
}
.section-to-print-body:not:first-child {
display: none;
}
.section-to-print-body~* {
z-index: 0;
display: none;
}
}
HTML
<div class="row infoAreaToPrint">
<!--Left column with Customer, Description, Quantity, FSC-->
<div class="col-lg-5">
<div class="card">
<div class="card-body">
<p class="h4 border-bottom mb-0">
Customer:</p>
<span>
<button onclick="printThisTableDiv('.infoAreaToPrint')">Print Info
</button>
</span>