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>
<title>JS print function</title>
<p>Hello World</p>
<button onclick="window.print()">Print</button>


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 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>


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;
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;

Run this code

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