Skip to content

The easiest way to print a specific area (element) of an HTML page

Published at  at 10:19 AM

Create printable Elements

<body>
  <div id="root">You can only see me on the page, typically powered by React or Vue.</div>
  <div class="print-only">You can only see me when printing.</div>
  <div class="printable">You can see me both on the page and when printing.</div>
</body>

Or create content using JavaScript:

const domToBePrinted = document.createElement("div");
domToBePrinted.classList.add("print-only");
// set the content
domToBePrinted.innerHTML = "...";
document.body.appendChild(domToBePrinted);

Add CSS

.print-only {
  display: none !important;
}

@media print {
  body > * {
    display: none !important;
  }
  .printable,
  .print-only {
    display: block !important;
  }
}

Invoke window.print() function

window.print();

If you want to set the content using JavaScript:

const domToBePrinted = document.createElement("div");
domToBePrinted.classList.add("print-only");

// set the content
domToBePrinted.innerHTML = "...";

document.body.appendChild(domToBePrinted);

window.addEventListener(
  "afterprint",
  () => {
    document.body.removeChild(domToBePrinted);
  },
  { once: true }
);
window.print();

If you want to change the filename of the content to be printed:

const originalTitle = document.title;
if (title) {
  document.title = title;
}
window.addEventListener(
  "afterprint",
  () => {
    document.title = originalTitle;
  },
  { once: true }
);
window.print();

Live Demo

Pros

Printing in React or Vue

See print-react-component

Share on: