Reputation: 5670
I have a page which displays many posts and allows the printing of a single post (a div
with all its children).
With clicking on the print button, I go through every element on the page and style it as follows:
The div to print is set to the class printme
which styles the top
and left
properties to 0 and sets position
to absolute
.
The div to print's children are left alone
If the element is a parent of the div to print, I add the class print-visibility-hide
which sets visibility: hidden
.
Otherwise, I add a class which sets display: none
. The output of this is shown below.
Everything works fine except that a blank page prints - which I am presuming is due to the parent divs using visibility: hidden
to hide content and therefore still taking up space.
Is there any way to print my div and somehow remove or collapse this extra space?
HTML - I end up with something like the following (with all the content removed for conciseness):
<body class="print-visibility-hide">
<div class="page-container print-visibility-hide">
<div class="main print-visibility-hide">
<div class="main-content d-section-top print-visibility-hide" id="main-content" style="background: transparent none repeat scroll 0% 0%; margin-left: 145px;">
<div id="gemwrapper" class="gemwrapper print-visibility-hide" style="display: block;">
<div class="gem-content-wrapper d-item d-section print-visibility-hide">
<div class="gem-content-main gems print-visibility-hide">
<div class="print-visibility-hide">
<div style="display: block;" id="s-g1353" class="print-visibility-hide">
<table class="print-visibility-hide">
<tbody class="print-visibility-hide">
<tr class="item tools print-visibility-hide">
<td class="textarea print-visibility-hide">
<div id="gparent1353" class="textarea print-visibility-hide">
<div id="gx1353" class="printme">
<pre>
This is the text I am printing which can be any length.</pre>
CSS
@media print {
body * {
visibility: hidden;
}
html,
body {
height: auto;
}
.print-display-none,
.print-display-none * {
display: none !important;
}
.print-visibility-hide,
.print-visibility-hide * {
visibility: hidden !important;
}
.printme,
.printme * {
visibility: visible !important;
}
.printme {
position: absolute;
left: 0;
top: 0;
}
.printme,
.printme:last-child {
page-break-after: avoid;
}
}
Upvotes: 5
Views: 32946
Reputation:
Use @media Print Like This :
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid;
page-break-before: avoid;
}
}
UPDATE 2:
Use This Code : Instead Of Your Code
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid !important;
page-break-before: avoid !important;
}
.print-display-none,
.print-display-none * {
display: none !important;
}
.print-visibility-hide,
.print-visibility-hide * {
visibility: hidden !important;
}
.printme,
.printme * {
visibility: visible !important;
}
.printme {
position: absolute;
left: 0;
top: 0;
}
}
Upvotes: 9