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?
JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.
JavaScript helps you to implement this functionality using the print function of window object. The JavaScript print function window. print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.
To print a page in JavaScript, use the print() method. It opens up the standard dialog box, through which you can easily set the printing options like which printer to select for printing.
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With