4

I currently run Rails 3.1 and am using the latest version of Wicked_pdf for PDF generation. I have set everything up correctly, and PDFs are generated just fine.

However, I want the user to be able to click a button to DOWNLOAD the pdf. At the present time, when clicked, the browser renders the pdf and displays it on the page.

<%= link_to "Download PDF", { :action => "show", :format => :pdf }, class: 'button nice red large radius', target: '_blank'%>

My Controller.

def show
    @curric = Curric.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @curric }
      format.pdf do
        render :pdf => @curric.name + " CV",
        :margin => {:top                => 20,  
                    :bottom             => 20 }

      end
    end
  end

I have been pointed towards send_file, but have absolutely no idea how to use it in this scenario.

Any help is appreciated.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
Ammar
  • 1,091
  • 12
  • 23

4 Answers4

13

Decomposition the config you need to set as 'attachment', example:

respond_to do |format|
  format.pdf do
    render pdf: @curric.name + " CV",
           disposition: 'attachment'
  end
end
aquajach
  • 2,548
  • 2
  • 23
  • 29
4

I am doing it that way:

  def show
    @candidate = Candidate.find params[:id]

    respond_to do |format|
      format.html
      format.pdf do
        @pdf = render_to_string :pdf => @candidate.cv_filename,
            :encoding => "UTF-8"
        send_data(@pdf, :filename => @candidate.cv_filename,  :type=>"application/pdf")
      end
    end    

  end

and it works for me ;-)

Johny
  • 1,441
  • 10
  • 26
  • The question is now, can I have multiple formats for the PDF that the user can choose between? – Ammar Dec 16 '11 at 13:12
  • I think you can, but then you have to pass it somehow as parameters. For example you cam name something like this `/candidates/1.pdf?type=extended` and then based on this parameter you can use different template to render it – Johny Dec 19 '11 at 16:25
3

Let's try:

pdf = render_to_string :pdf => @curric.name + " CV",
                       :margin => {:top     => 20,  
                                   :bottom  => 20 }
send_file pdf
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • When Using Send_File I get ` ArgumentError (string contains null byte):`. However, when I change it to send_data I get the pdf downloading. However, when I use send_data, the pdf's save as [curric_id].pdf where [curric_id] is the id of the resource. :( – Ammar Oct 27 '11 at 22:59
  • @Ammar send_file(pdf, :filename => 'whatever.pdf') – Unixmonkey Oct 28 '11 at 19:51
0
//Download pdf generated from html template using wicket_pdf gem 
pdf = render_to_string :template => "simple/show" // here show is a show.pdf.erb inside view

send_data pdf
Roney Michael
  • 3,964
  • 5
  • 30
  • 45
Sartaj Singh Sisodiya
  • 1,143
  • 12
  • 10