Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect background-image and background-color support when printing from browser

When printing a page from a browser, it refers to a print.css stylesheet declared with media="print". The browser disables some CSS rules like background-image and background-color, some browsers have options to enable them.

As told in this answer, it is not possible to override this behaviour from the page code.

I have two questions about this:

  • Is there any documentation or good reference about these printing rules ? For example:
    • Which CSS rules are disabled ?
    • Can Javascript do something on the page before printing ?
  • Is there a way to detect a browser in printing mode with Javascript and then make a graceful degradation system ?
like image 913
ldiqual Avatar asked May 17 '12 22:05

ldiqual


1 Answers

How browsers print pages is a bit of a black box; I haven't been able to find any definitive references.

All major browsers have print options to "shrink to fit" the web page to the paper page (enabled by default), and to print background images and colours (disabled by default). Most users will leave these defaults as-is, if they are even aware these options exist. I haven't seen browsers "disabling" any other CSS rules when printing.

Firefox and IE support the onbeforeprint and onafterprint events, so you can detect when printing is happening with JavaScript, though obviously this isn't a cross-browser solution.

Most adjustments needed for printing can be handled by CSS (either in a separate print stylesheet or as a @media print { ... } block in your main stylesheet):

  • The CSS-Discuss Wiki has a good page on how much you can control through CSS.

  • I suggest having a look at the print styles from HTML5 Boilerplate as a good starting point.

  • If you have background images that must be printed, you can include <img> elements in your page, hidden with display: none, then make them visible with display: block (or inline) in your print CSS.

If you need to heavily modify the page for printing, I suggest offering a separate print-only version of the page, rather than trying to make adjustments with JavaScript.

like image 108
Jeffery To Avatar answered Oct 18 '22 01:10

Jeffery To