如何在不使用Rails中的respond_to format.pdf的情况下呈现PDF?

Isr*_*ael 0 pdf ruby-on-rails render prawn ruby-on-rails-3

如何在不渲染此文件的情况下向客户端发送文件(PDF,CSV等)?

例如,想象一下学生控制器(使用脚手架创建),我们有'新'形式和'创建'动作:

  def new
    @student = Student.new
    respond_to do |format|
      format.html # new.html.erb
    end
  end

  def create
    @student = Student.new(params[:student])
    respond_to do |format|
      if @student.save
        flash[:notice] = 'Student created'
        format.html { redirect_to(@student) }
      else
        format.html { render :action => "new" }
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

成功创建学生后,它将重定向到"显示"模板.那没问题!但我需要发送给客户端 - 例如PDF文件,然后呈现'show'动作.

此PDF文件类似于客户端的创建收据.

额外信息:现在使用Prawn制作PDF并通过以下代码发送给客户:

    respond_to do |format|
      format.pdf { render :layout => false }
    end
Run Code Online (Sandbox Code Playgroud)

总之,我需要获得填写的表格,创建学生,PDF发送到浏览器(作为创建收据)和渲染"秀"的行动,以显示创建学生.

非常感谢你.

小智 5

这是我使用wicked_pdf的解决方案.

这会创建pdf但不会下载它.将PDF保存到文件.将链接保存在数据库中,使用显示的链接重新呈现视图(视图显示@plan).

    # create a unique PDF filename
    pdf_uuid = UUIDTools::UUID.timestamp_create().to_s
    pdf_uuid_filename = Rails.root.join('public/pdf', "#{pdf_uuid}.pdf").to_s

    # create a pdf but don't display it
    pdf_file = render_to_string :pdf => pdf_uuid_filename, 
                                :template  => 'plans/show.pdf.erb' ,
                                :layout    => 'pdf',
                                :save_only => true
    # save to a file
    File.open(pdf_uuid_filename, 'wb') do |file|
      file << pdf_file
    end
    # create full URL path to created file  
    @plan.url = request.url[0, request.url.index("plans")] +  'pdf/' + CGI::escape("#{pdf_uuid}.pdf")
    @plan.save!
    # render the page again with the link being displayed
    redirect_to :back
Run Code Online (Sandbox Code Playgroud)