I have a button that once clicked opens a new window, writes html to that window and then sends a print command to it.
$("#print-preview").on("click", ".preview-print-btn", function(e){
e.preventDefault();
var printHtml = $("#print-preview-container").html();
var w = window.open(" ");
w.document.write(printHtml);
w.print();
w.close();
});
Now what I also need to do is add a @page
styling to the head of that new window. Specifically a background image. This image is not a static one and could be anything the user uploads it to be. I've tried with both jQuery and javascript to add a style element to the head of the new window.
The javascript solution I tried (taken from here):
var style = w.document.createElement('style');
w.document.head.appendChild(style);
style.innerHTML = '@page { background: url(' + bgUrl + ') 50% 50% no-repeat; }';
And a jQuery solution I tried:
$(w.document).find("head").append('<style type="text/css">@page { background: url(' + bgUrl + ') 50% 50% no-repeat; }</style>');
Update:
Since by default I wasn't passing the entire document, only the html content, that was needed for printing, I also tried passing the entire html document to the new window:
var printHtml = '<!DOCTYPE html><html><head><style>@media print { @page { background: url(\'' + bgUrl + '\') center center repeat; } }</style></head><body>';
printHtml += $("#print-preview-container").html();
printHtml += '</body></html>';
But this didn't work aswell as no background is being rendered.
How can I add a style element to a document that is opened in a new window?