Monday, November 12, 2012

Hiding elements from printing

The question comes up all the time: Can I prevent people from printing my web page or an image on the page?  The short answer is unfortunately "No".  You can make it difficult for them, but a determined visitor will still find ways.  So far nothing I'm aware of can prevent them altogether.  Basically, if you put it on the page, they can see it and find a way to print it.

Another way of looking at the same problem is removing elements of your page that don't need to be printed.  For instance, if somebody is reading an article on your site and wants to print it, they probably don't need the navigation, advertisements or a print button on the printed page.  They want to read the article, not look at the framework around it.

If you are simply trying to hide certain elements from the printed page, such as a navigation menu, or the print button itself, you can use CSS to tell the browser not to print those sections.  That way, anyone who uses normal methods of printing the page won't see what you don't want them to.

To do this, you need to add a section to your CSS, called a media rule.
Now, depending on your preference and needs, there are several ways you can write your CSS within that rule. For example, if you want to add a class to certain elements and hide those from the printed page, you could write it like this: Now anything in your HTML that you don't want printed you add the "noPrint" class. That can be applied to almost any element on your page. It will appear as normal in the browser window, but will be removed from the printed page.
On a related topic, sometimes people will ask how to block users from downloading images from their page. The same answer applies here as well... you can put up roadblocks, but somebody determined enough can still get a copy of the image. There are many variations on how to do this, but most involve intercepting what is called the context menu (the menu displayed when you right-click) and returning false. This technique is easily defeated, doesn't work in all browsers anyway, and in most cases will only serve to annoy your users, more than prevent them from doing what they wanted in the first place. Rather than show an example of how to do this, I suggest that if you need to prevent somebody from right-clicking on an image for a valid reason, you would be better spending your time re-thinking why the image is on the page in the first place if you need to keep it protected.

See it in action!

Experiment with this at http://jsfiddle.net/webdevem/jP5Gb/

No comments:

Post a Comment