Is it possible to print something with a printer with javascript in the browser?
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.
Thanks
Window print() Method The print() method prints the contents of the current window. The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.
Page print in JavaScript is a simple code in JavaScript used to print the content of the web pages. The print() method prints the contents of the current window. It basically opens Print dialog box which lets you choose between various printing options.
To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted.
The window. print() method calls the browser's build in print support plugin to print the current DOM page. you can check the documentation, it doesn't support any argument or settings. to setup the print, you can only utilize the browser's GUI( ex. enable or disable background graphics etc.)
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:
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)
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);
You can't access print settings from within the browser.
This is due to security considerations, otherwise printers worldwide would be printing non-stop.
The only thing you can do regarding printing in javascript in call window.print();
.
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