I am creating a pdf file in the latest version of the Prawn library (v1.0.1rc) in Rails (3.1.1) and when I run my code it generates the PDF into the root of the application.
I don't want this. I want it to render the output into user's browser window, without saving it locally to the server.
Please tell me how I can achieve this. Here are my files:
views/foo/show.pdf.erb:
<%=
require 'prawn'
pdf = Prawn::Document.new(:page_size => 'LETTER', :page_layout => :landscape, :margin => 50, :top_margin => 20, :bottom_margin => 50)
.....
render_file("foo.pdf")
%>
controllers/foo_controller:
class AuditsController < ApplicationController
before_filter :authenticate_user!
layout 'application'
can_edit_on_the_spot
respond_to :html, :xml, :js, :pdf
def index
@audits = Audit.all
respond_with @audits
end
def show
@audit = Audit.find(params[:id])
respond_with @audit do |format|
format.pdf { render :layour => false }
end
end
Gemfile
/config/initializers/mime_types.rb
AuditsController
I used to use the
prawnto
gem before Rails 3.1, but it doesn't work without a bit of hacking anymore. This is a much cleaner way to instantiate and display the PDF object in 3.1 by accessing Prawn directly.I got this technique straight from one of Ryan Bates' Railscasts. Been using it ever since. You can view that specific episode here. He goes into much more detail about subclassing Prawn and moving the PDF generating code out of the controller. Also shows a lot of useful Prawn methods to get you started. Highly recommended.
A lot of the episodes are free, but that revised Prawn episode is one of those that are only available with a paid subscription. At $9/month though, a subscription quickly pays for itself.
I find the best way to send a pdf to the client's browser is to put the download into a link. Often you need to generate a pdf after form submission, but also need to redirect to another page.
You can't redirect and send the pdf simultaneously, but you can redirect and then provide a download link, like so:
First add
gem 'prawn'
to your gemfile. Bundle. Then do the following:Link to your special printing action in your view
route to special printing action in routes.rb
action that sends the outputted file (change per your needs):