How to print the content of current window using JavaScript ?
The task is to print the content of the current window by using the window.print() method in the document. It is used to open the Print Dialog Box to print the current document. It does not have any parameter value.
Syntax:
window.print()
Parameters: No parameters are required
Returns: This function does not return anything
Example: This example representing how to print the content of current window using JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GeeksForGeeks - Print Page</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
color: #4CAF50;
}
h3 {
color: #2196F3;
}
.btn {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
.btn:hover {
background-color: #45a049;
}
@media print {
.no-print {
display: none;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Hello GeeksForGeeks Users</h1>
<h3>Print the content of the current window
using HTML and JavaScript
</h3>
<p>This is a sample paragraph that will be included in
the printed page. You can add more content here as needed.
</p>
<form class="no-print">
<input type="button" class="btn"
value="Print Page"
onclick="printCurrentPage()" />
</form>
</div>
<script>
function printCurrentPage() {
window.print();
}
// Add a listener for the beforeprint event
window.addEventListener('beforeprint', function() {
console.log('Printing started');
});
// Add a listener for the afterprint event
window.addEventListener('afterprint', function() {
console.log('Printing finished');
});
</script>
</body>
</html>
Output: