在rails应用程序中保存prawn pdf

时间:2015-08-28 07:20:46

标签: ruby-on-rails prawn

我正在使用prawn gem生成PDF,我在我的应用程序展示页面show.html.slim中有此链接 = link_to "PDF", post_path(@post, :format => 'pdf'), :target => "_blank

我的帖子控制器显示方法

def show
@post = post.find(params[:id])
respond_to do |format|
    format.html # show.html.erb
    format.pdf { render :layout => false}
end

我的show.pdf.prawn页面有:

font("app/assets/fonts/DejaVuSans.ttf") do

table [["Title \n #{@post.title}"], [''], ['Summary']], cell_style: {  size: 14, bold: :true }, row_colors: ['F0F0F0'], column_widths: [540] do
row(0).align = :center
row(0).size = 16
row(0).background_color = '93AAD9'
self.header = true

row(2).align = :center
row(2).background_color = 'DEB8A5'

end

...

我希望当我去显示页面时,pdf会自动保存到我的应用中的app/assets/pdf folder

请建议。

2 个答案:

答案 0 :(得分:0)

respond_to阻止后添加prawn保存:

filename = File.join(Rails.root, "app/assets/pdf_folder", "x.pdf")
send_file filename, :filename => "x.pdf", :type => "application/pdf" 

答案 1 :(得分:0)

您似乎可以使用render_to_string对架构进行最少的修改:

# controller code
format.pdf do
  filename = Rails.root + "app/assets/posts/#{params[:id].to_i}.pdf"
  unless File.exists?(filename)
    File.write(filename, render_to_string)
  end

  send_file filename, :filename => "post_#{params[:id].to_i}.pdf", :type => "application/pdf"
end