开发者

Using Prawn & Prawnto for Rails PDF generation

开发者 https://www.devze.com 2022-12-14 01:32 出处:网络
This is probably more a design or usage question but the main issue is using the Prawn plugin with Rails 2.3.4 and accessing the resulting PDF object to render it to a file.

This is probably more a design or usage question but the main issue is using the Prawn plugin with Rails 2.3.4 and accessing the resulting PDF object to render it to a file.

The scenario is basically;

  • a controller with the respond_to block setup
  • a view with code for rendering the text, graphics etc to PDF

It looks like:

From Customer Controller

def show    
    @customer = Customer.find(params[:id])  

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @customer }
      format.pdf  { render :layout => false  }
end

From Customer View

  pdf.text "Hello World"  
  pdf.text "Customer is #{@customer.name}"

This works fine, producing a PDF file in response to /customers/1.pdf, as expected with a PDF file being generated.

One of the other requirements is to render the pdf to a file and 开发者_如何转开发store a copy on the server. Prawn provides the method: pdf.render_file {path_tofile}

So now if I include this in the View code I can of course save the file on the server. But I'd like to manage this in the controller, as it's related to logic, not view per se.

The first attempt was :

def show    
   @customer = Customer.find(params[:id])
   @pdf = Prawn::Document.new()  

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @customer }
      format.pdf  { render :layout => false  }
      pdf.render_file {path_to_file}
end

From Customer View

  pdf.text "Hello World"  
  pdf.text "Customer is #{@customer.name}"

PROBLEM The problem with this attempt is that the PDF is not rendered. I suspected the Controller instance variable is clashing with the Prawnto Plugin pdf variable. But even changing the PDF variable didn't work. Any suggestions ?


This is how I use prawn in my rails app: http://yob.id.au/2009/05/30/prawn-and-x-accel-redirect.html - it doesn't use prawnto at all.

You can ignore the X-Accel-Redirect stuff unless you use nginx.

Alternatively, another one of the prawn core devs has put together this guide: http://wiki.github.com/sandal/prawn/using-prawn-in-rails

0

精彩评论

暂无评论...
验证码 换一张
取 消