Portix.One

guide · javascript

How to Print from JavaScript

By Portix.One Published
JavaScript code calling window.print() to send a prepared document to a printer

Quick answer

Attach window.print() to a clear user action, finish loading data, fonts, and images first, and define an @media print stylesheet. The method takes no arguments and does not return a job result. Use it for user-confirmed pages and PDF. Use a local runtime, native app, managed kiosk, or print service when the application must select a printer, print silently, send device commands, or monitor jobs.

JavaScript can start the browser’s print workflow with window.print(). The page prepares content and print CSS; the browser lets the user select a destination and settings. Automatic printer routing, raw commands, and reliable job status require a trusted integration outside this standard API.

1. Add a print action

<button id="print" type="button">Print</button>
<script>
  document.querySelector("#print").addEventListener("click", () => {
    window.print();
  });
</script>

2. Add print CSS

@media print {
  .screen-only { display: none !important; }
  body { color: #000; background: #fff; }
  article { max-width: none; }
  h2 { break-after: avoid-page; }
  figure, table { break-inside: avoid-page; }
}

@page { margin: 12mm; }

3. Wait for required assets

async function printDocument() {
  await document.fonts.ready;
  await Promise.all(
    [...document.images]
      .filter(image => !image.complete)
      .map(image => image.decode())
  );
  window.print();
}

Handle rejected image decoding according to whether the asset is required.

4. Use lifecycle events sparingly

window.addEventListener("beforeprint", preparePrintOnlyState);
window.addEventListener("afterprint", restoreScreenState);

Prefer CSS for visual changes. afterprint does not confirm physical delivery.

5. Choose the correct architecture

RequirementApproach
User selects printer/PDFwindow.print()
Print one elementDedicated print document or print CSS
Silent named-printer routingTrusted runtime/native/kiosk integration
Raw ESC/POSAuthorized binary transport
Job status and retryQueue/runtime/service

Common mistakes

  • Calling print before rendering completes.
  • Opening print automatically on page load.
  • Printing screen navigation and controls.
  • Assuming @page forces device settings.
  • Treating dialog closure as success.
  • Building a popup that browsers block.

Frequently asked questions

Can JavaScript choose the printer?

Not through window.print(). The user chooses in browser/platform UI.

Can JavaScript print silently?

Not through the standard API on an ordinary page.

Can I print only a component?

Yes, by hiding unrelated content in print CSS or rendering a dedicated print document.

References

Related content