Posted on 10-10-2008
Filed Under (inglês, ruby on rails) by Rafael Uchôa

Yes, by a very, very simple way! First of all, you don’t need to worry about document’s layout, you will use your own View! Let’s see how.

Before anything, you need to install a command-line program that can convert any XML to PDF, called Prince XML. The program is distributed under a free license and can generate PDF files based on XHTML with CSS applied. See the site for more details.

There is a lot of interfaces to connect your app to PrinceXML. For Ruby On Rails, you can use Princely. In your Rails app, run the git command

git clone git://github.com/mbleigh/princely.git vendor/plugins/princely

Don’t worry if you don’t have any idea how to use GIT (like me! :-),  this command only copies the plugin to your application.

Talking about the plugin, it will register PDF MimeType so you can call your action with .pdf extension on URL.

So, your Contoller’s action needs to be something like this:

  # GET /books/1
  # GET /books/1.xml
  def show
    @book = Book.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @book }
      format.pdf {
            render :pdf => @book.title,
                   :template => "books/show.pdf.erb"
      }
    end
  end

Now, any request with extesion .pdf will return a PDF file to client. In the View, you can especify the format of link_to function, just like this:

<%= link_to 'Show PDF', book_path(@book, :format => :pdf) %>

And it’s done!

Have fun y hasta luego!

    Read More   
Post a Comment
Name:
Email:
Website:
Comments: