gabriel
gabriel

Reputation: 21

Using CSS while printing a page using javascript

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.

Upvotes: 2

Views: 398

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76508

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"

Upvotes: 2

Related Questions