Javascript打印功能如何工作?可以使用javascript创建文档并将其打印出来吗? [英] How does the Javascript print function work? Can I create a document using javascript and print it off?

查看:111
本文介绍了Javascript打印功能如何工作?可以使用javascript创建文档并将其打印出来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以使用window.print()来打印当前页面,但是我想知道的是,我可以使用javascript来构建一个文档,以便使用数据填充它并打印出来吗?



就像您可以将HTML / xml作为JavaScript对象一样,可以执行类似的操作:

  var name =Matt; 
var htmlDocumentToPrint =< html>< body>< div style ='width:300px; height:20px; background-color:#000; text-align:center;'>我的名字是 + name +< / div>< / body>< / html>;

htmlDocumentToPrint.print();

我真的不在乎添加颜色 - 只是想格式化文档,用数据填充它,并将其打印出来。这是可能吗?

解决方案

Print()是一个窗口对象的方法。如果您使用javascript在窗口中创建文档,请在该窗口对象上调用print,它应该可以工作。

 < script类型= 文本/ JavaScript的 > 
var myWindow = window.open('','','width = 200,height = 100')
myWindow.document.write(this is'myWindow')
myWindow 。打印();
< / script>

w3schools.com 窗口打开示例。


I know you can use window.print() to print the current page... but what I want to know is can I build a document using javascript in order to populate it with data and print it off?

Just like you can have html/xml as a javascript object, can you do something similar to this:

var name = "Matt";
var htmlDocumentToPrint = "<html><body><div style='width:300px; height:20px; background-color:#000; text-align:center;'>My name is " + name + "</div></body></html>";

htmlDocumentToPrint.print();

I don't really care about adding colors all that much-- just want to format a document, populate it with data, and print it off. Is this possible?

解决方案

Print() is a method on the window object. If you create a document in a window using javascript, then call print on that window object, it should work.

<script type="text/javascript">
    var myWindow = window.open('','','width=200,height=100')
    myWindow.document.write("This is 'myWindow'")
    myWindow.print();
</script>

Example modified from w3schools.com window open example.

这篇关于Javascript打印功能如何工作?可以使用javascript创建文档并将其打印出来吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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