Printing Div Content with CSS Applied

Print div id=printarea/div only?

Here is a general solution, using CSS only, which I have verified to work.

@media print {
body * {
visibility: hidden;
}
#section-to-print, #section-to-print * {
visibility: visible;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}

Alternative approaches aren't so good. Using display is tricky because if any element has display:none then none of its descendants will display either. To use it, you have to change the structure of your page.

Using visibility works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move section-to-print to the top left so it prints properly.

How to apply css to print div

at last I found an answer. I don't know the reason why @media was not working correctly. So I used css styling in the print function itself.

w.document.write('<style>h1{font-size:20px;color:#76C04E;width:90%;}</style>');
w.document.write('<style>body{background: #FFFFFF; color: #000000; font: 85% arial, verdana, helvetica, sans-serif; }</style>');

w.document.write('<style>.res td{font-size: 12px;font-family: open sans, arial; border-top: 1px solid #ddd; width: auto;padding: 4px;} </style>');

Now the css is correctly taken in the print preview page.
But it works only in firefox.Will update the answer accordingly when I find the solution for chrome

Thanks.

Print the contents of a DIV

Slight changes over earlier version - tested on CHROME

function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');

mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>' + document.title + '</h1>');
mywindow.document.write(document.getElementById(elem).innerHTML);
mywindow.document.write('</body></html>');

mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/

mywindow.print();
mywindow.close();

return true;
}

How to print an specific DIV with its CSS

You can select all other elements and hide them from the page (excluding the target with the use of the :not() CSS pseudo class), then call window.print() to print the page:

btn.addEventListener('click', function(){
document.body.querySelectorAll(':not(.red)').forEach(e => e.style.display = "none");
window.print();
})
div{
height:100px;
border:1px solid;
}
.red{
background-color:red;
}
.blue{
background-color:blue;
}
<div class="red">
red
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>


Related Topics



Leave a reply



Submit