How to Print File in JavaScript (Send to Printer)
To print the current HTML page in JavaScript call the window.print()
function. Here is an example of an HTML print button and a JavaScript print()
function that opens a print dialogue for the user.
<button type="button" id="print">Print</button>
var btn = document.getElementById('print');
btn.addEventListener('click', function() {
window.print();
});
That's it! Now you can put a print button on any page and the user can print everything that is on the page as it is displayed in the browser window.
Printer Friendly Example
You might want the print function to get a printer friendly version. To do this in JavaScript, open a new tab using the window.open()
function, set the HTML body of the new document and call print()
on the object.
var btn = document.getElementById('print');
btn.addEventListener('click', function() {
let text = window.open();
text.document.body.innerHTML = 'some content.';
text.print();
});