2

The title is a little confusing but basically I have a PHP page with css applied, I use javascript to take a div(form) and print it using the print() function just like so.

function printform(form){
    var printdata = document.getElementById(form);
    newwin = window.open("");
    newwin.document.write(printdata.outerHTML);
    newwin.print();
    newwin.close();
}

The page pops up but I want to use the css of the PHP page which I can't seem to get working. I have tried using a rel to get the css file (tried the absolute path as well) and delaying the printing but it didn't work (code below).

function printform(form){
    var printdata = document.getElementById(form);
    newwin = window.open("");
    newwin.document.write(printdata.outerHTML);
    newwin.document.write('<html><head>');
    newwin.document.write('<link rel="stylesheet" href="css/css.css" type="text/css" media=\\"all\\" />');
    newwin.document.write('</head><body >');
    newwin.document.write('</body></html>');
    setTimeout(function(){newwin.print();},1000);
    newwin.focus();
}

How can I make the css appear on the other page?

I can give more context if needed.

2
  • Shouldn't printdata.outerHTML get written between the <body> and </body> tags? Commented Jun 14, 2022 at 20:17
  • I've tried putting inside the body and it did change much. Commented Jun 15, 2022 at 13:54

1 Answer 1

2

First, you need to make sure that your content is in the body:

function printform(form){
    var printdata = document.getElementById(form);
    newwin = window.open("");
    newwin.document.write('<html><head>');
    newwin.document.write('<link rel="stylesheet" href="css/css.css" type="text/css" media=\\"all\\" />');
    newwin.document.write('</head><body >');
    newwin.document.write('</body>' + printdata.outerHTML + '</html>');
    setTimeout(function(){newwin.print();},1000);
    newwin.focus();
}

Second, your media=\\"all\\" seems to be incorrect, you need to change it to media="all" or media="print"

Sign up to request clarification or add additional context in comments.

2 Comments

Tried putting the content in the body just like shown and even tried changing it like this: newwin.document.write('</head><body >'); newwin.document.write(printdata.outerHTML + '</body></html>'); Still doesn't do anything about the css
@gabriel I've confirmed in a test environment that this solution works. Did you fix the "media" attribute? And did you confirm that the style sheet is in a subfolder named "css"? You might also want to try prefixing the CSS path with a slash, e.g. "/css/css.css".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.