As other people have said, it's hard to understand your problem without seeing a working example of the problem, but just guessing the code:
- The browser cannot load CSS before calling
print()
. - The browser cannot display CSS before calling
print()
.
Keeping in mind changing your JS function this way you can do the trick
function printDiv(divId) { $("link").clone().appendTo($("#print_frame").contents().find("head")); window.frames["print_frame"].document.body.innerHTML = printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost; window.frames["print_frame"].window.focus(); var windowInstance = window.frames["print_frame"].window; setTimeout(function() { windowInstance.print(); }, 0); }
The idea behind this function is to let the browser execute its code after adding changes to the HTML / CSS code in the window - see Why is setTimeout (fn, 0) used sometimes?
WARNING: this approach is not tested for your specific problem, and it may also not work, because we avoid / leave the stack of mouse click calls, calling the print()
method may not be possible from the user interaction stack.
UPDATE: after viewing in jsfiddle - my assumption was correct, the browser needs some time to load and display CSS, so calling print()
immediately after changing the contents of the iframe does not give the desired result. There are 3.5 ways to solve this:
- Use events to determine when the iframe and window have finished loading and rendering. I tried two approaches and still could not read them, I need to read the documents more carefully when the documents and the window behave during the loading sequence:
- we can do this from outside the iframe, that is, listen to the events of the
iframe
element and its children - we can do this from within an iframe, i.e. add a small javascript fragment inside which a message will be sent to the parent window at boot time.
- Think about how to shape the print result differently, how about sheets of print styles? That is, to add another stylesheet with a print request to the parent document and just invoke printing on it?
- Consider forming an iframe that is already loaded and ready to print, but replace only the contents of the table inside it.
source share