41 lines
2.1 KiB
Markdown
41 lines
2.1 KiB
Markdown
+++
|
|
date = "2007-01-19"
|
|
title = "“Print this page” with Ruby on Rails"
|
|
tags = ["General", "Everything", "RubyOnRails", "Features"]
|
|
slug = "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:
|
|
<!--more-->
|
|
|
|
<pre lang="ruby">stylesheet_link_tag('default', :media => :screen)
|
|
stylesheet_link_tag('print', :media => :print)</pre>
|
|
|
|
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?
|
|
|
|
<ul>
|
|
<li>Fonts should be serif (not sans-serif) for printing</li>
|
|
<li>Hide images as much as possible</li>
|
|
<li>Hide ads</li>
|
|
<li>Display printable ads that are hidden on screen</li>
|
|
<li>Hide navigational elements</li>
|
|
<li>Use a black-on-white colour scheme</li>
|
|
<li>Underline links and colour them blue for easy recognition</li>
|
|
<li>Add the actual URL to your links (see below)</li>
|
|
</ul>
|
|
|
|
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:
|
|
|
|
<pre lang='css'>a:after { content:' [' attr(href) '] '}</pre>
|
|
|
|
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:
|
|
|
|
<pre lang="ruby">link_to_function("Print this Page", "javascript:print()")</pre>
|
|
|
|
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.
|
|
|