4Geeks chosen to deliver AI education in the Bahamas alongside Harvard, Oxford, and Columbia.See more

How to print a page in JavaScript with window.print()

By 4Geeks

Print the page or save it as PDF with window.print(), control what goes on paper with @media print and print values with console.log().

6 min readLast updated
Print in JavaScript icon

How do you print in JavaScript?

Short answer: to print the page, call window.print(). It opens the browser's print dialog, the same one you get with Ctrl + P (Cmd + P on macOS):

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

If by "print" you mean showing a value while you code, use console.log(): it writes to the browser console or the terminal.

javascript
console.log("Hello");  // Hello

window.print() opens the print dialog and @media print decides what the printed page looks like.

Every way to print in JavaScript

What you wantCodeWhere it appears
Print the page or save it as PDFwindow.print()The browser's print dialog
Show a value while you debugconsole.log(value)Console (F12) or terminal
Show data as a tableconsole.table(array)Console
Show text on the pageelement.textContent = "Hi"The page
Show a pop-up messagealert("Hi")A browser dialog
Change what gets printed@media print { ... } in CSSThe printed page

window.print() takes no arguments and returns nothing. It opens the print dialog for the current page, where the user chooses a printer or Save as PDF:

html
<button id="print-btn">Print invoice</button>
 
<script>
  document.getElementById("print-btn").addEventListener("click", () => {
    window.print();
  });
</script>

A few things to know:

  • JavaScript can't print without the dialog or choose the printer. The user always confirms.
  • Call it from a click or another user action, so the dialog doesn't take the user by surprise. Browsers can block dialogs that open again and again.
  • The page waits while the dialog is open: code after window.print() usually runs when the dialog closes.
Career · AI Engineering

You already print and log in JavaScript, now build with AI

From zero to junior AI Engineer: Python, data, AI agents and RAG with mentors and real projects.

Choose what gets printed with @media print

The printed page uses the same HTML, but you can change its CSS. Rules inside @media print only apply when printing:

css
@media print {
  nav, footer, .no-print {
    display: none;   /* hide menus and buttons */
  }
  body {
    font-size: 12pt;
    color: black;
  }
  a::after {
    content: " (" attr(href) ")";   /* show link URLs on paper */
  }
}

Add the class no-print to anything you don't want on paper, such as the Print button itself. To start a new page before an element, use break-before: page;.

The simplest way is CSS: hide everything except the part you want while printing.

css
@media print {
  body * { visibility: hidden; }
  #invoice, #invoice * { visibility: visible; }
  #invoice { position: absolute; left: 0; top: 0; }
}

Then window.print() prints only #invoice. Another option is to open a new window with only that content and print it:

javascript
function printSection(id) {
  const html = document.getElementById(id).innerHTML;
  const win = window.open("", "", "width=800,height=600");
  win.document.write(html);
  win.document.close();
  win.focus();
  win.print();
  win.close();
}

This second way loses your page's styles unless you add them to the new window.

Run code before and after printing

The beforeprint and afterprint events let you prepare the page and restore it:

javascript
window.addEventListener("beforeprint", () => {
  document.title = "Invoice-1042";   // suggested PDF file name
});
 
window.addEventListener("afterprint", () => {
  console.log("The print dialog was closed");
});

afterprint fires when the dialog closes, whether the user printed or canceled. JavaScript can't tell which one happened.

When you're learning, "print" usually means showing a value to check your code:

javascript
const user = { name: "Ana", age: 28 };
 
console.log("Hello");          // Hello
console.log("Age:", user.age); // Age: 28
console.table([user]);         // the object as a table
console.error("Oops");         // shown in red as an error

In the browser, open the console with F12 (or Cmd + Option + J in Chrome on macOS). In Node.js, the output goes to the terminal where you ran node app.js.

To show text on the page itself, change an element instead:

javascript
document.getElementById("result").textContent = "Total: $77.00";

Avoid document.write(): if it runs after the page has loaded, it erases the whole page.

Use AI to set up printing

An assistant like ChatGPT, Claude or GitHub Copilot can write the print CSS for your page. These three prompts are ready to copy.

1. Print CSS

This is my HTML: [paste it]. Write a @media print stylesheet that hides [the menu / the buttons /
the footer], fits the content on A4 paper and shows the URLs of the links.

2. Print one section

I want a button that prints only the element with id "[id]" of my page, keeping its styles.
Show me the HTML, CSS and JavaScript, and explain the trade-offs.

3. Fix a print problem

When I print my page with window.print(), [describe the problem: cut tables, missing colors,
blank pages]. This is my CSS: [paste it]. Explain why and fix it.

Check the result in the print preview before you ship it.

Learn with a mentor

From printing pages and logs to AI applications

In the 4Geeks AI Engineering career program you start with no experience and finish with AI agents and RAG systems in your portfolio.

Common problems when printing in JavaScript

What you seeWhy it happensFix
Nothing happens when window.print() runsIt was not called from a user action, or the page is in a sandboxed iframeCall it from a click handler
Buttons and menus appear on paperThe print CSS doesn't hide themHide them inside @media print
Background colors are missingBrowsers skip backgrounds to save inkAdd print-color-adjust: exact; (and -webkit-print-color-adjust: exact; for older browsers)
A table is cut between pagesRows break across pagesUse break-inside: avoid; on the rows
The page went blankdocument.write() ran after the page loadedUse textContent or innerHTML instead
console.log shows nothingThe console is closed, or you're looking at the wrong tabOpen it with F12 and check the Console tab
ReferenceError: window is not definedYou ran browser code with Node.jsRun it in the browser; Node.js has no window
Free download

Printing in JavaScript in a 2-page cheat sheet

window.print(), print CSS, printing one section, beforeprint and afterprint, console methods, common problems and prompts for ChatGPT, Claude or Copilot. Free, in PDF.

How to print in JavaScript cheat sheet

2 pages · PDF · 4Geeks

  • The code to print a page or one section
  • Print CSS that hides menus and keeps tables whole
  • Common problems and prompts to solve them with AI

Get it free

Your PDF right away

Frequently asked questions about printing in JavaScript

Want to go from browser APIs to building AI apps, with real projects and mentors?

See the AI Engineering program