开发者

Rails and Prawn PDF - add current item ID to filename?

开发者 https://www.devze.com 2023-01-02 07:49 出处:网络
I have two PDFs that are made \"on the fly\" using Prawn PDF. The PDFs are called jobsheet.pdf and discharge.pdf - their URLs are:

I have two PDFs that are made "on the fly" using Prawn PDF.

The PDFs are called jobsheet.pdf and discharge.pdf - their URLs are:

railsroot/kases/IDNO/jobsheet.pdf
railsroot/kases/IDNO/discharge.pdf

I am trying to work out how to automagically append the filename with the ID number:

railsroot/kases/IDNO/jobsheet_IDNO.pdf
railsroot/kases/IDNO/discharge_IDNO.pdf

To create the PDFs the code is as follows:

Kases Controller

def jobsheet
    @kase = Kase.find(params[:id])

    respond_to do |format|
      format.html {} # jobsheet.html.erb
      format.xml  { render :xml => @kase }
      format.pdf { render :layout => false }

      prawnto :prawn => { 
                 :background => "#{RAILS_ROOT}/public/images/jobsheet.png", 
                 :left_margin => 0, 
                 :right_margin => 0, 
                 :top_margin => 0, 
                 :bottom_margin => 0, 
                 :page_size => 'A4' }
    end

  end

  # GET /kases/1
  # GET /kases/1.xml
  def discharge
    @kase = Kase.find(params[:id])

    respond_to do |format|
      format.html { } # discharge.html.erb
      format.xml  { render :xml => @kase }
      format.pdf { render :layout => f开发者_如何学Goalse }

      prawnto :prawn => { 
                 :background => "#{RAILS_ROOT}/public/images/discharge.png", 
                 :left_margin => 0, 
                 :right_margin => 0, 
                 :top_margin => 0, 
                 :bottom_margin => 0, 
                 :page_size => 'A4' }
    end

  end

Routes

 map.resources :kases, :member => { :discharge => :get }
  map.resources :kases, :member => { :jobsheet => :get }

To view the PDFs I use the following links:

jobsheet_kase_path(@kase, :format => 'pdf')
discharge_kase_path(@kase, :format => 'pdf')

Is this even possible?

Thanks,

Danny


From the prawnto documentation it looks like the prawnto method supports passing a file name as part of the options hash. So you should be able to do something like this:

def jobsheet 
  @kase = Kase.find(params[:id]) 

  respond_to do |format| 
    format.html # jobsheet.html.erb 
    format.xml { render :xml => @kase } 
    format.pdf { render :layout => false } 

    prawnto :filename => "jobsheet_#{@kase.id}", :prawn => {  
      :background => "#{RAILS_ROOT}/public/images/jobsheet.png",          
      :left_margin => 0,  
      :right_margin => 0,  
      :top_margin => 0,  
      :bottom_margin => 0,  
      :page_size => 'A4' } 
  end 
end 


If not using prawnto, the following works for prawn-rails and prawn_plus.

# in format.pdf
headers["Content-Disposition"] = "attachment; filename=\"file-#{model.id}.pdf\""
0

精彩评论

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