Send a javascript variable to the printer containing the HTML code inside

Suppose I have a variable like this in JavaScript:

var h = "<html><head></head><body><h1>Example</h1><p>This is a variable I want to print to the printer with the browser!</p></body></html>" 

How can I send the pretty visualized content of this variable to the printer?

I tried:

 var w = window.open(); 

and then:

 $(w).html(h); 

and then:

 w.print(); 

But the fact is that a pop-up blocker is blocking my new window on the print page. A.

Does anyone have any ideas?

Thank you very much!

+6
source share
3 answers

Now, as a rule, I would not do it all inline. But for this question it became easier for me to read this way. Basically set up a media stylesheet that allows the printable area. then assign your html to this div. Now that the print has been deleted, the message #printableArea will be sent to the printer.

 <html> <head> <style type="text/css"> #printableArea { display: none; } @media print { #non-printableArea { display: none; } #printableArea { display: block; } } </style> <script type="text/javascript"> $(document).ready(function () { var h = "<html><head></head><body><h1>Example</h1><p>This is a variable I want to print to the printer with the browser!</p></body></html>"; $("#printableArea").html(h.find("body").html()); }); </script> </head> <body> <div id="printableArea"></div> <div id="non-printableArea"></div> </body> </html> 
+2
source

This is one way to solve this problem: http://jsfiddle.net/DerekL/Fn2Yh/

 var h = "<h1>Example</h1><p>This is a variable I want to print to the printer with the browser!</p>"; var d = $("<div>").addClass("print").html(h).appendTo("html"); window.print(); d.remove(); @media only print{ body{ display: none; /*using @media will mess up the page if the user wants to*/ } /*print the page normally. If that the case you would */ } /*want to set the display of the body to none manually. 

By placing the content that should be printed outside the body , you can now simply hide the entire document, leaving the content you need to display.


OOP: http://jsfiddle.net/DerekL/sLQzd/

+3
source

Instead of adding a new window, you can add a special print area to your web page, which is only visible when printing. A.

http://jsfiddle.net/cp3zS/

HTML

 <div class="non-printable"> Foo </div> <div class="printable"> </div> 

CSS

 @media screen { .printable { display: none;} .non-printable { display: block;} } @media print { .non-printable { display: none;} .printable { display: block;} } 

Js

 var h = "<html><head></head><body><h1>Example</h1><p>This is a variable I want to print to the printer with the browser!</p></body></html>" $('.printable').html(h); window.print(); 
+2
source

All Articles