Skip to content

ES6 - Page Printing

JavaScript provides a simple way to allow users to print the content of the current web page using the window.print() method. This method opens the browser’s standard print dialog, allowing the user to select a printer and configure print settings.

The window.print() function can be easily triggered by a button click or other user interaction.

The following HTML code demonstrates how to add a button that, when clicked, will invoke the print dialog for the current page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Printing Example</title>
<style>
/* Basic styling for the page */
body { font-family: Arial, sans-serif; margin: 20px; }
.printable-content { border: 1px solid #eee; padding: 15px; }
.no-print { margin-top: 20px; }
/* CSS for print media */
@media print {
body { margin: 0; font-size: 12pt; }
.no-print { display: none; } /* Hide elements not meant for printing */
.printable-content { border: none; }
h1 { color: black; }
}
</style>
</head>
<body>
<h1>Web Page Content</h1>
<div class="printable-content">
<p>This is the main content of the page that will be printed.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="no-print">
<button id="printButton">Print this Page</button>
</div>
<script>
document.getElementById('printButton').addEventListener('click', () => {
window.print();
});
</script>
</body>
</html>

When you open this HTML file in a browser and click the “Print this Page” button, the browser’s print dialog will appear. The content within the div with class printable-content will be part of the print preview. The button itself (inside the div with class no-print) will be hidden in the printed output due to the @media print CSS rules.

It’s often necessary to style the page differently for printing than for screen display. You can use CSS @media print rules to apply specific styles when the page is printed. Common use cases include:

  • Hiding non-essential elements like navigation bars, footers, or buttons (as shown with the .no-print class in the example).
  • Changing font sizes, colors, and layout for better readability on paper.
  • Ensuring backgrounds and images are printed correctly if desired.
  • Expanding collapsible content or showing URLs for links.

By combining window.print() with thoughtful CSS print styles, you can provide a good user experience for printing web pages.