Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

Printout a page in Javascript



Printing a page with JavaScript can be achieved using the window.print() method. This method opens the print dialog box, which allows the user to choose the printer and settings.

Basic Syntax

javascript
window.print();

Example

Here's a simple example of how you can add a button to your web page that, when clicked, will trigger the print dialog:

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Example</title>
</head>
<body>

<h1>Hello, World!</h1>
<p>This is a sample page to demonstrate printing with JavaScript.</p>

<button onclick="window.print()">Print this page</button>

</body>
</html>

In this example:

  • The window.print() method is called when the button is clicked, which opens the print dialog.

Adding Print-Specific Styles

You can also define print-specific styles using the @media print CSS rule to ensure that your page looks good when printed.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Example with Styles</title>
<style>
  @media print {
    body {
      font-size: 14pt;
      color: black;
    }
    h1 {
      font-size: 18pt;
    }
    button {
      display: none;  /* Hide the print button when printing */
    }
  }
</style>
</head>
<body>

<h1>Hello, World!</h1>
<p>This is a sample page to demonstrate printing with JavaScript.</p>

<button onclick="window.print()">Print this page</button>

</body>
</html>

In this example:

  • The @media print rule is used to apply styles only when the page is printed.

  • The print button is hidden using display: none; so it doesn't appear on the printed page.

Feel free to ask if you need more information or help with any specific use case!




All rights reserved | Privacy Policy | Sitemap