从前端的JavaScript打印? [英] Print from frontend javascript?

查看:132
本文介绍了从前端的JavaScript打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以打印一些与在浏览器中使用JavaScript的打印机?

Is it possible to print something with a printer with javascript in the browser?

我要打印收据号码,因此,如果可能的话,什么是速度最快的打印机,当在用户点击按钮可打印出如。 1234的小文。

I want to print a receipt number, so if it's possible, what is the fastest printer so when the user clicks on a button it will print out eg. "1234" on a small paper.

感谢

推荐答案

您不能直接从JavaScript访问打印机,但你可以叫 window.print()这将启动标准浏览器的打印行为。用这种方法,你可以尝试两种技术来实现你追求的:

You can't access the printer directly from Javascript but you can call window.print() which will initiate the standard browser print behaviour. Using this, you could try two techniques to achieve what you're after:

就在打电话之前 window.print()注入一个动态的打印样式表只显示与你想打印文本的元素。您需要小心清理任何previous打印样式表。或者其实你可以只使用一个元素< D​​IV ID =打印> 这是唯一可见的元素在打印样式表并插入任何文本中印那。 (只是要留意,如果这是一个网站,用户实际上可能想打印)

Just before calling window.print() inject a dynamic print stylesheet that only shows the elements with the text you're wanting to print. You would need to be careful to cleanup any previous print stylesheets. Or in fact you could just use an element <div id="printable"> which is the only visible element in your print stylesheet and insert any text to be printed in that. (Just be mindful if this is a website which users may actually want to print)

这也是可能的打印()直接调用一个iframe窗口,你可以用你想要的文字填充上。例如:

It's also possible to call print() directly on an iframe window, which you could populate with your desired text. For example:

var iframe = document.createElement('iframe');

iframe.onload = function() {
    var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
    doc.getElementsByTagName('body')[0].innerHTML = "<p>1234</p>";

    iframe.contentWindow.focus(); // This is key, the iframe must have focus first
    iframe.contentWindow.print();
}

document.getElementsByTagName('body')[0].appendChild(iframe);

这篇关于从前端的JavaScript打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆