Trigger printing of a web page in JavaScript

NicolasBrondinBernard

Author
@NicolasBrondinBernard

4 tips for improving the paper printouts of your web application.

Article published on 10/08/2021, last updated on 10/08/2026

Depending on your web application's target audience, your users may regularly ask to print one or more of your pages.

Take the tax website for example, many users will want to print their payment receipt page!

Today we're going to discover several tips for improving the paper printing experience on your site:

Triggering printing

Instead of letting the user search through their browser's options for the print feature, you can integrate a button yourself into your application to trigger printing with the following native function:

window.print();

Note: doing this will trigger the browser's native print window, but not the printing itself.

Displaying images/background colors

You may discover that the page doesn't display correctly in the print preview; this is because, to save ink, the browser automatically hides images and certain background colors.

If you use the background-image method to position certain images, they won't be displayed unless you add the following two properties to your css:

* {
  color-adjust: exact;
  -webkit-print-color-adjust: exact;
}

Modifying the style for printing

Depending on the design, there's a good chance that printing on paper as-is won't be very readable, for example because of shadows, certain colors, etc., or that there are elements with no interest when printed (links, buttons, navigation bar, etc.).

Fortunately, there's a media query called "print" that will let you add a specific style to modify or hide certain elements, only when printing!

@media print {
  ...
}

There are also Javascript events "onbeforeprint" and "onafterprint" that can be used to do the same things, but it's advised to use them only as a last resort.

Avoiding page breaks

Since the print rendering is directly tied to a specific paper size, some of your graphic elements may end up split across two pages, causing the information to lose its coherence.

With the "break-inside" property in CSS, you can tell your browser to avoid cutting a particular graphic element in two, even if it means forcing a premature page break:

.card {
  break-inside: avoid;
}

Museums Victoria sur Unsplash

Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet