将包含HTML代码的JavaScript变量发送到打印机

7
假设我在JavaScript中有一个变量如下:

var variableName = 10;

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>"

我该如何将此变量的漂亮渲染内容发送到打印机?

我尝试过以下方法:

var w = window.open();

接着:

$(w).html(h);

然后:

w.print();

但问题在于弹出窗口拦截器阻止了我的打印页面的新窗口。有人有什么想法吗?非常感谢!

问题是变量包含HTML还是弹出窗口阻止了你的新窗口?到目前为止,我不确定我是否理解了这个问题。 - blurfus
我的问题是弹出窗口拦截器。也许还有其他方法。 - tpgalan
对于回答这个问题的每个人都加1分,而且所有答案都是正确的。我的问题是,我也试图用"<html>"和"<style>"标签来“注入”HTML代码。通过删除它们并使用这些CSS规则将其写入源页面,一切都顺利进行了。谢谢大家。 - tpgalan
3个回答

3
这是解决此问题的一种方法: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's the case you would  */
}                        /*want to set the display of the body to none manually.

通过将要打印的内容放在标签外,您现在可以简单地隐藏整个文档,只显示所需的内容。
面向对象编程(OOP):http://jsfiddle.net/DerekL/sLQzd/

2

通常我不会这样直接写。但为了这个问题的目的,我觉得这样更容易阅读。基本上设置一个媒体样式表,允许打印区域。然后将你的html分配到该div中。现在当点击打印时,只有#printableArea会被发送到打印机。

<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>

谢谢。这很棒,但我的变量包含了所有的<html>标签和<style>标签... - tpgalan

2

不必添加新窗口,您可以在网页上添加一个特殊的打印区域,在打印时才可见。

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接