Let's say I'd like to print (or convert to PDF) a particular area (e.g., a div) of a complex HTML page. How to do that in Chrome or Firefox? I didn't find a specific option from the "inspect element" function.
Let's say I'd like to print (or convert to PDF) a particular area (e.g., a div) of a complex HTML page. How to do that in Chrome or Firefox? I didn't find a specific option from the "inspect element" function.
I know it's a quite an old topic, but here is what worked for me:
<div id="parent_div">
<p>NOT to be printed</p>
<div id="print_div">
Print this!
</div>
<button id="print_now" onclick="PrintDiv('print_div')">
</div>
And the JS function:
function PrintDiv(div_id) {
$('body').css("visibility", "hidden");
$("#"+div_id).css("visibility", "visible");
window.print();
$('body').css("visibility", "visible");
}
If you are not using jQuery, you can still change the CSS with:
document.getElementById("body").style.visibility = "hidden";
document.getElementById(div_id).style.visibility = "visible";
By using a print only media query, which is a feature introduced in CSS3
Assuming it is identified by either an id or class selector, you apply display: none to it, and not visibility: hidden, since display controls not only the exibition of the element, it also controls the space occupied in the document, unlike visibility, which hides it but still lets it occupy its space.
So it should look somewhat like this:
#container {
background-color: blue;
padding: 1rem;
}
#display-test {
background-color: lightgreen;
}
#visibility-test {
background-color: lightblue;
}
#display-test,
#visibility-test {
color: white;
padding: 1rem;
margin: 1rem 0 1rem 0;
}
#print-display-test,
#print-visibility-test {
color: white;
display: none;
}
@media only print {
#display-test {
display: none;
}
#visibility-test {
visibility: hidden;
}
#print-display-test,
#print-visibility-test {
display: block;
}
}
<div id="container">
<div id="display-test">
This is a display test
</div>
<span id="print-display-test">
This is going to show at the start of the page
</span>
<div id="visibility-test">
This is a visibility test
</div>
<span id="print-visibility-test">
This is going to show far apart from the text above
</span>
<br>
<button type="button" onclick="window.print()">
Print this
</button>
</div>