This code snippet helps you to create a without opening print document. It defines a function called printDocument that can be used to print the contents of an HTML element or multiple elements on a web page. The function checks if an element ID is provided, and if so, it fetches the innerHTML of the element(s) and opens a new window to print the content. The new window is resized to fit the screen, and then the print method is called to print the content. If no element ID is provided, the function simply calls the window.print() method to print the entire page.
How to Create JavaScript Print Document Without Opening
Create the HTML structure for the printed document as follows:
<p>Codebrary printing demo</p>
<input type='button' id='btn' value='Print Full Page' onclick='printDocument("");'>
<input type='button' id='btn2' value='Print Paragrapph 1' onclick='printDocument("divToPrint1");'>
<input type='button' id='btn3' value='Print Paragraph 1 and 2' onclick='printDocument("divToPrint1,divToPrint2");'>
<div id='divToPrint1'>
<p>1. This is a sample 1 text from codebrary for printing.</p>
</div>
<div id='divToPrint2'>
<p>2. This is a sample 2 text from codebrary for printing.</p>
</div>
<a href="https://www.codebrary.com">www.codebrary.com</a>
Now, style the printed document using the following CSS styles:
.cd__main{
display: block !important;
}
Finally, add the following JavaScript function for its functionality:
//Use this function on click event and provide id of the element to print or leave it blank.
// Example: printDocument("") OR printDocument("myDivId") OR printDocument("myDivId1, myDivId2")
function printDocument(elemid) {
//Check if element is empty
if (elemid == "") {
window.print();
}
else {
//array to store ids separated with comma if available
var arrelemid = elemid.split(',');
var htmlContent = "";
for (var i = 0; i < arrelemid.length; i++) {
htmlContent += document.getElementById(arrelemid[i]).innerHTML;
}
//Window Width (ww) and Window Height (wh) of the user's screen, in pixels
var ww = screen.availWidth;
var wh = screen.availHeight - 90;
//Print Window (pw)
var pw = window.open("", "newWin", "width=" + ww + ",height=" + wh);
pw.document.write('<html><title>Printed Page</title><body>');
pw.document.write('</head><body>');
pw.document.write(htmlContent);
pw.document.write('</body></html>');
pw.document.close();
pw.print();
pw.close();
// Created by Sartaj Husain for www.codebrary.com
}
}
That’s all! hopefully, you have successfully created the JavaScript print document without opening. If you have any questions or suggestions, feel free to comment below.
