9

is there a way to print css styles, that are inline?

I use this code to print part of the code:

w=window.open();
w.document.write($('#printable').html());
w.print();
w.close();

I could use external file and make it media=print, but part of the html are chars, that are generated by php and I could make it by making class for every posible outcome, but that would be pain.

Any ideas? Thanks.

5
  • is it necessary to open a popup? Commented Aug 11, 2011 at 22:05
  • No, it's neccecery to print the <div id='printable'> Commented Aug 11, 2011 at 22:07
  • 1
    Would you clarify your goal? You say you are trying to separate out all the inline CSS styles from an HTML document and print them to a printer? Or you're just trying to do a sort of "Print Source" task that sends the entire HTML of a page to the printer for the user? Commented Aug 11, 2011 at 22:08
  • All I want is to print the selected div only. The way it is displayed in browser. Commented Aug 11, 2011 at 22:09
  • Please see my answer I gave you. Commented Aug 11, 2011 at 22:18

2 Answers 2

13

See the Demo: http://jsfiddle.net/rathoreahsan/x69UY/

What do you think if you do like this:

<div id="printableDiv">
    <style type="text/css">
        @media print {
            #printable { 
               color: red; 
               // Any Other style you want to add 
             }
        }
    </style>
    <div id="printable">
        This Text will print in red color.
    </div>
</div>

Javascript/jQuery code:

w=window.open();
w.document.write($('#printableDiv').html());
w.print();
w.close();

In this scenario while a popup opens and gets the HTML of printableDiv, the styles for printer will be included in that popup so the printer will read styles from popup and will print in that manner.

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

1 Comment

Well, there are 2 things, why I can't use this code. The main thing is, that this way I'd have to give class .noprintable to every element on the page, that I don't want to print, which is no possible. The second thing is, that it doesn't solve the problem, that I need to print the inline css.
0

I had the same problem, because i use instyle style to dynamically change background-color, and then the color was not in the print. styleSheets[3] is my print.css file.

This worked for me: I uncluded it in the smarty foreach i use to give some elements a background color.

<script type='text/javascript'>
  document.styleSheets[3].insertRule(" #caldiv_<?smarty $item.calendar_id ?> { border-color:<?smarty $item.color ?> }", 1);
</script>

Comments

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.