【问题标题】:Wicked_PDF Download Only - Rails 3.1Wicked_PDF 仅下载 - Rails 3.1
【发布时间】:2011-12-16 10:28:26
【问题描述】:

我目前运行的是 Rails 3.1,并且正在使用最新版本的 Wicked_pdf 生成 PDF。 我已经正确设置了所有内容,并且生成了 PDF。

但是,我希望用户能够单击一个按钮来下载 pdf。目前,当点击时,浏览器呈现pdf并显示在页面上。

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

我的控制器。

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

我一直指向 send_file,但完全不知道如何在这种情况下使用它。

感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails pdf ruby-on-rails-3.1 sendfile wicked-pdf


    【解决方案1】:

    让我们试试吧:

    pdf = render_to_string :pdf => @curric.name + " CV",
                           :margin => {:top     => 20,  
                                       :bottom  => 20 }
    send_file pdf
    

    【讨论】:

    • 使用 Send_File 时,我得到 `ArgumentError (string contains null byte):`。但是,当我将其更改为 send_data 时,我会下载 pdf。但是,当我使用 send_data 时,pdf 保存为 [curric_id].pdf,其中 [curric_id] 是资源的 id。 :(
    • @Ammar send_file(pdf, :filename => 'whatever.pdf')
    【解决方案2】:

    我就是这样做的:

      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
    

    它对我有用 ;-)

    【讨论】:

    • 现在的问题是,我可以为 PDF 提供多种格式供用户选择吗?
    • 我认为你可以,但是你必须以某种方式将它作为参数传递。例如,您可以使用类似 /candidates/1.pdf?type=extended 的名称命名,然后根据此参数,您可以使用不同的模板来渲染它
    【解决方案3】:
    //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
    

    【讨论】:

      【解决方案4】:

      分解你需要设置为'attachment'的配置,例如:

      respond_to do |format|
        format.pdf do
          render pdf: @curric.name + " CV",
                 disposition: 'attachment'
        end
      end
      

      【讨论】:

      • 这就是答案...其他选项都不起作用。
      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2014-07-13
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多