Jil Jil - 4 months ago 11
Javascript Question

Print a HTML page using Window.print

I have been trying to get this done from long. I have a HTML page with few icons and upon clicking print I want the page to be printed including the icons.

I did as per the solution suggested in the Print specific



But in this I am not able to load the icons and also the page formatting goes haywire. Any suggestions on how to get the page printed upon click without having to play around with the already formatted/styled page.

The application has a cshtml file which has the styles, icons referenced which again need not be referenced to in each html page I create. So when I call
window.print()
the styles are not loaded as that specific
div
which I want to be printed, does not load the icons which the action is called for. My question is in such case where the styles are defined once for the entire application, how do I call the
window.print()
?

Answer
var win = window.open('','printwindow');
    win.document.write('<html><head><title>Print it!</title><link rel="stylesheet" href="http://localhost:8080/fin/pcd/css/printlib.css" type="text/css" /><link rel="stylesheet" href="css/main.css" type="text/css" /></head><body>');
    win.document.write($("#"+divid+"key").html());
    win.document.write($("#"+divid2+"line").html());
    win.document.write('<div class="testPrint"></div><script>;</script></body></html>');
    win.print();

Using above you can print specific divs and import css where you can apply necessary styles(including your icons) to the div.

Some more info added:

Check the below working example link you would get some idea: https://plnkr.co/edit/f1JkCgYvI10rsdm5msmM?p=preview

Note: if background-color is given to the css of the page to be printed the concerned attribute would only work if background graphics is enabled for chrome and is not needed for other browsers.

Check below image on how to enable background graphics in chrome:

enter image description here