How to print a web page using JavaScript

This article shows how to print the contents of a web page using JavaScript. To print a web page, we use the window.print() function.

How to print a web page using JavaScript

Sometimes we would like to print some important content on the web page via a printer. We can use the print() function of window object to print a web page.

window.print() function

The window.print() function prints the contents of the web page. This example shows how to use window.print() function in the click event of a button.

Example 1 – Printing a simple page

<!DOCTYPE html>
<html>
<head>
   <title>JS print function</title>
</head>
<body>
    <p>Hello World</p>
    <button onclick="window.print()">Print</button>
</body>
</html>

Output

Hello World

Example 2 – Printing in a different page size

To print the page in a specific page size you can follow this method.

HTML markup

<div>
    <div class="page">
        <div class="page-inner">
            <p>This is a page with the size of an A4 page</p>
            <button id="mybutton" onclick="window.print()">Print</button>
        </div>   
    </div>
</div>

Add CSS

body {
    margin: 0;
    padding: 0;
}
* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}
.page {
    width: 21cm;
    min-height: 29.7cm;
    padding: 2cm;
    margin: 1cm auto;
    border: none;
    background: #F4F3F1;
}
.page-inner{
    padding: 1cm;
    border: 2px solid black;
    height: 256mm;
    outline: 2cm #F4F3F1 solid;
}

@page {
    size: A4;
    margin: 0;
}
@media print {
    .page {
        margin: 0;
        border: initial;
        border-radius: initial;
        width: initial;
        min-height: initial;
        box-shadow: initial;
        background: initial;
        page-break-after: always;
    }
}
#mybutton{
background-color:dodgerblue;
border:none;
padding:10px;
color:white;
}

Run the code

See the Pen Printing a web page using JavaScript by Mishel Shaji (@mishelshaji) on CodePen.


Share Tweet Send
Loading...