Print Div with Javascript and Style Preservation

I am trying to print a specific div in my application using this javascript with jQuery:

function PrintContent() { w=window.open(); w.document.write($('#diary').html()); w.print(); w.close(); } 

It opens the div on a new tab, and the print options panel opens, but the CSS styles are lost. I have print.css set for media = "print", however, I think that it doesn’t explicitly load this file in a new tab, that is, it just loads the div and not the header where the CSS is located.

Any idea how I can fix this? My javascript is not so strong.

Thanks!

+4
source share
2 answers

Try using this line instead:

 w.document.write('<div id="diary">' + $('#diary').html() + '</div>'); 

You are writing the internal html of your div, not the div tag.

The method above also writes the div tag with the correct id. I just pinned the identifier because you could format the div#diary and not the div .

EDIT

This method should keep the style.

 function PrintContent() { var e = document.createElement('div'); e.id = 'diary'; e.innerHTML = $('#diary').html(); document.getElementById('t').appendChild(e); } 

You just need to make space so that this content can be inserted, for example a div with id t . As in the example that I posted in the comments.

+3
source

Since document.write is a bad practice:

https://github.com/jasonday/printThis

0
source

Source: https://habr.com/ru/post/1335055/


All Articles