【问题标题】:Send to the printer a javascript variable containing HTML code inside it向打印机发送一个包含 HTML 代码的 javascript 变量
【发布时间】:2014-06-22 05:08:28
【问题描述】:

假设我在 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>"

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

我试过了:

var w = window.open();

然后:

$(w).html(h);

然后:

w.print();

但问题是弹出窗口阻止程序用打印页面阻止了我的新窗口。

有人知道吗?

非常感谢!

【问题讨论】:

  • 问题是包含 HTML 的变量还是弹出窗口阻止程序不允许您的新窗口?到目前为止我不确定我是否理解这个问题。
  • 我对这种方法的问题是弹出窗口阻止程序。也许可能存在其他一些方法
  • 回答这个问题的每个人都+1,而且都是正确的。我的问题也是,试图用“”和“

标签: javascript jquery html printing


【解决方案1】:

现在通常我不会在内联中做这一切。但是出于这个问题的目的,我觉得以这种方式阅读更容易。基本上设置一个允许可打印区域的媒体样式表。然后将您的 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>

【讨论】:

  • 谢谢。这可能很棒,但我的变量包含其中的所有 标签以及
【解决方案2】:

这是解决此问题的一种方法: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.

通过将要打印的内容放在body 之外,您现在可以简单地隐藏整个文档,只显示您需要的内容。


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

【讨论】:

    【解决方案3】:

    您可以在网页中添加一个特殊的打印区域,而不是添加新窗口,该区域仅在打印时可见。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2016-02-09
      • 2019-01-27
      • 2023-03-22
      • 2011-01-03
      相关资源
      最近更新 更多