Last updated

“Print this page” with Ruby on Rails

You have put a lot of effort into creating a sexy overview of whatever data your application stores and allow your users to manipulate that data through AJAX controls. But, some people just want to print their data.

How to go about that? Just printing the page with data is generally not a good idea because it has been optimized for display on a screen. The first step we need to take is adapting our page for printing. Stylesheets are very handy tools for this. Check the following part of the header of my layout:

1stylesheet_link_tag('default', :media => :screen)
2stylesheet_link_tag('print', :media => :print)

This will generate HTML code that includes two stylesheets. However, only the ‘default’ stylesheet is used on screen. When the users prints a particular page, the print stylesheet is used instead. So, what do you want to change in the print stylesheet?

  • Fonts should be serif (not sans-serif) for printing
  • Hide images as much as possible
  • Hide ads
  • Display printable ads that are hidden on screen
  • Hide navigational elements
  • Use a black-on-white colour scheme
  • Underline links and colour them blue for easy recognition
  • Add the actual URL to your links (see below)

To add the actual URL in the href-part of your link to the name of your link add the following to you print stylesheet:

a:after { content:' [' attr(href) '] '}

Now, with all this in place, load your page with data. Print your page or watch a preview and be amazed at what stylesheets can do for you!

The final touch is adding a “Print this page” link to your navigation on screen. Here you can use link_to_function:

1link_to_function("Print this Page", "javascript:print()")

That’s it. Just hit the Print this Page button and your browsers print dialog will pop up and use your fancy new print stylesheet.