I am working on a project and I want to print div content.The code which I am using is fulfilling my requirements,but I am getting simple output without Css applied to it an
A possible cause of your rendering issue may be due to the relative paths you're using for the CSS file and images. First, try to use absolute paths. The fact that the HTML structure is rendered excludes problems with the generation of the new HTML document. Also, add media="print"
to the link
element.
This code works, though partially:
(function() {
function createPopup( data ) {
var mywindow = window.open( "", "new div", "height=400,width=600" );
mywindow.document.write( "<html><head><title></title>" );
mywindow.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\"/>" );
mywindow.document.write( "</head><body >" );
mywindow.document.write( data );
mywindow.document.write( "</body></html>" );
mywindow.print();
//mywindow.close();
return true;
}
document.addEventListener( "DOMContentLoaded", function() {
document.getElementById( "print" ).addEventListener( "click", function() {
createPopup( document.getElementById( "content" ).innerHTML );
}, false );
});
})();
I've removed the .close() call. Bear in mind that some CSS styles may not work with print.
If you wanna render the CSS you must add a timeout before printing it because it takes some time for CSS to be applied to the HTML and then you will be able to print it.
Try this:
function Popup(data) {
var mywindow = window.open('', 'new div', 'height=400,width=600');
mywindow.document.write('<html><head><title></title>');
mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
setTimeout(function(){mywindow.print();},1000);
mywindow.close();
return true;
}