has moved and is now available at

“Print this page” with Ruby on Rails

19 January 2007

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:

stylesheet_link_tag('default', :media => :screen)
stylesheet_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?

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:

link_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.