Rtf::Rails

Rtf::Rails provides a simple way of creating RTF views in Rails 3 using the rtf library.

To use Rtf::Rails simply add the line

gem 'rtf_rails'

to your Gemfile and then run

bundle install

That’s it! You can now create views named

[action].rtf.rtf_rb

which will be used whenever the user requests a page with a ‘rtf’ extension

Usage

Basic Usage

Rtf::Rails is designed to provide only a very thin wrapper around Rtf itself. A Rtf::Rails view should consist of only a call to the function rtf_document and a block. This will create an instance of Rtf::Document and yield it to the block. For a simple rtf view try:

views/…/simple.rtf.rtf_rb

rtf_document() do |rtf|
  rtf << "Hello World"
end

This will create a simple PDF with only the text Hello World.

Partials

While layouts do not yet work with Rtf::Rails, partials work fine. Rendering a partial is much like in a normal view. For example:

views/…/partial.rtf.rtf_rb

rtf_document do |rtf|
  render "frontpage", :rtf => rtf
  rtf << "something else"
end

views/…/_frontpage.rtf.rtf_rb

rtf << "frontpage action!!"

As you might expect this will result in a rtf with a leading page.

Instance Variables

Like normal Rails views, instance variables assigned in the controller are made available in the view. For example:

home_controller.rb

class HomeController < ApplicationController
  def index
    @people=['Jane','John','Jack']
  end
end

views/…/index.rtf.rtf_rb

rtf_document(:page_layout => :landscape) do |rtf|
  @people.each {|person| rtf << person}
end

This will produce a rtf with Jane, John, and Jack all written on seperate lines.

Force Saving

The :force_download option makes the browser display a ‘save as’ dialog rather than attempting to display the content in browser (this is achieved by setting the Content-Dispoition header).

views/…/saveas.rtf.rtf_rb

rtf_document(:force_download=>true) do |rtf|
  rtf << "Hello World"
end

Finally is the :filename option. This allows you to override the default filename to something other than the name of the action. Note: You should include the .rtf extension in the filename. Rtf::Rails will not do this for you.

views/…/filename.rtf.rtf_rb

rtf_document(:filename=>'Hello.rtf') do |rtf|
  rtf << "Hello World"
end

This will result in the user being promted to download a file named ‘Hello.rtf’.

Gotchas

The one major gotcha at this point is that layouts do not work. Do not attempt to make an app/views/layouts/application.rtf.rtf_rb. All your rtf views will quit. This is something I hope to fix in a later release. In the meantime I recommend using custom classes like the one above to achieve a similair effect.

Copyright © 2012 MonsterLabs, released under the MIT license