Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Javascript print function work? Can I create a document using javascript and print it off?

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?

like image 332
Matt Avatar asked Aug 07 '09 21:08

Matt


People also ask

How do you print using JavaScript?

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.

What is the print function in JavaScript?

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.

Which JavaScript method is used to print a page?

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.

How do you create a function in JavaScript?

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, ...)


1 Answers

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.

like image 197
tvanfosson Avatar answered Oct 27 '22 01:10

tvanfosson