How to print in JavaScript

One of the common functions in web development is printing content directly from a web page.

In this article, you will have to learn the different methods on how to print in JavaScript.

If you need to print a document, a specific section of a page, or generate a printable version of your web content.

Also, JavaScript provides powerful solutions to meet your printing requirements.

Methods to Print in JavaScript

Here are the following methods to print in JavaScript:

1. Printing a Full Web Page

To print the full web page using JavaScript, you can use the window.print() method.

This method triggers the browser’s print functionality, allowing the user to select a printer and configure print settings.

Here’s an example code of how to use window.print():

function printPage() {
  window.print();
}

By calling the printPage() function, the browser’s print dialog will open, allowing the user to print the current web page.

2. Printing a Specific Section

Sometimes, you may only want to print the exact section of a web page rather than the whole content.

To produce this, you can create a print style sheet and apply it to the focus section.

This style sheet should determine the specific styles for printing.

Here’s an example code:

<link rel="stylesheet" type="text/css" media="print" href="print.css">

In the print.css file, you can define the styles for the section you want to print. By applying the media=”print” attribute to the tag, the browser will only use this style sheet when printing.

3. Generating a Printable Version

Another method for printing in JavaScript is to generate a printable version of your web content.

This method enables you to customize the appearance and layout of the printable version.

You can construct a separate HTML template that represents the printable content and constantly populate it with the important data.

Here’s an example code:

function generatePrintableVersionExample() {
  // Retrieve data and format it accordingly
  
  // Create a new window for the printable version
  const printableWindowSample = window.open('', '_blank');
  
  // Write the printable content to the new window
  printableWindowSample.document.write(`
    <html>
      <head>
        <title>Printable Version</title>
        <!-- Additional stylesheets and meta tags for print -->
      </head>
      <body>
        <!-- Printable content goes here -->
      </body>
    </html>
  `);
  
  // Close the document after printing
  printableWindowSample.document.close();
  
  // Trigger print
  printableWindowSample.print();
}

By calling the generatePrintableVersionExample() function, a new window will open with the printable content, and the browser’s print dialog will pop up.

4. Customizing Print Output

When printing in JavaScript, you may need to customize the print output to match your specific needs.

Here are some simple customization options:

Paper Size and Orientation

You can define the paper size and orientation for the printed content using CSS.

By applying the @page rule in your print stylesheet, you can control different aspects of the print layout, such as size, margins, and orientation.

Here’s an example CSS program:

@page {
  size: A4 landscape;
  margin: 2cm;
}

Page Breaks

To control page breaks within the printed content, you can use the page-break CSS properties.

These properties enable you to determine where the page breaks should occur, and it will ensure proper pagination.

Let’s see an example:

@media print {
  .page-break {
    page-break-after: always;
  }
}

In your HTML, you can use .page-break class to illustrate where a page break should happen.

Headers and Footers

You can add headers and footers to the printed pages using the @top-left, @top-center, @top-right, @bottom-left, @bottom-center, and @bottom-right CSS properties.

These properties enable you to include additional information, such as page numbers or document titles, in the print output.

5. Handling Print Events

JavaScript offers window.onbeforeprint and window.onafterprint events, which enables you to perform actions before and after the print dialog is demonstrated to the user.

These events are useful when you need to change the content or perform several tasks based on the print action.

For example:

window.onbeforeprint = function() {
  // Perform actions before print
};

window.onafterprint = function() {
  // Perform actions after print
};

By determining the functions for these events, you can add custom action to your print functionality.

FAQs

How do I check if the print dialog is open?

To define if the print dialog is open, you can use the window.matchMedia() method.

Can I print specific elements with JavaScript?

Yes, you can print exact elements by using the window.print() method in combination with CSS media queries.

By applying proper styles to the elements you want to print, you can obtain the selective printing.

Is it possible to customize the print layout for different browsers?

Yes, you can focus the specific browsers or browser versions by using CSS media queries.

By applying various styles for each targeted browser, you can obtain the browser-specific print layouts.

Can I print images using JavaScript?

Yes, you can print images using JavaScript by including them in the printable content or applying proper styles to show them only in the print output.

Conclusion

In conclusion, printing content from a web page using JavaScript is a powerful feature that increases the user experience and provides flexibility in generating printable versions.

In this article, we have learned the methods on how to print in JavaScript. From printing a full web page to customizing print output and handling print events, JavaScript offers a range of possibilities.

Additional Resources

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Leave a Comment