Store system-generated PDF on S3

半世苍凉 提交于 2019-12-10 14:39:38

问题


Solved, see edit at bottom.


In my 3.1 rails app I'm generating a pdf like this:

def show
  @contributor = Contributor.find(params[:id])

   respond_to do |format|
   format.pdf { 
    html = render_to_string(:action => "show.html.erb") 
    kit = PDFKit.new(html) 
    kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/unique/print.css" 
   thepdf = send_data kit.to_pdf, :filename => "blah.pdf", :type => 'application/pdf' 
redirect_to :action => save_to_s3      
}
end

Then I'm trying to store that generated PDF on S3 by uploading with Paperclip:

def save_to_s3
     html = render_to_string(:action => "show.html.erb") 
      kit = PDFKit.new(html) 
      kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/unique/print.css" 
      roy = Royarchive.new(:client_id => @contributor.client_id) 
      f = File.open("blah.pdf", 'w+')
      f.write kit.to_pdf
      roy.pdf = f
      roy.save!
end 

But that's giving me "\x9C" from ASCII-8BIT to UTF-8

How can I use Paperclip to upload this generated pdf to S3? I'm using Heroku so I can't save a temp file on the server then upload it.

////solved

Oh, my bad, you can store files for the duration of the session at root.

So this works:

   def show
  @contributors = Contributor.where(:client_id => current_user.client_id).paginate(:page => params[:page])
  @contributor = Contributor.where(:client_id => current_user.client_id).find(params[:id])


   respond_to do |format|
   format.html 
    format.pdf { 
    html = render_to_string(:action => "show.html.erb") 
    kit = PDFKit.new(html) 
    kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/unique/print.css" 
    send_data kit.to_pdf, :filename => "name.pdf", :type => 'application/pdf' 
    @thepdf = kit.to_file("#{Rails.root}/tmp/name.pdf")

roy = Royarchive.new(:client_id => @contributor.client_id) 
roy.pdf = @thepdf
roy.save!     
  }   

end
end

回答1:


Oh, my bad, you can store files for the duration of the session at root.

So this works:

def save_to_s3
  html = render_to_string(:action => "show.html.erb") 
   kit = PDFKit.new(html) 
   kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/unique/print.css" 
  thepdf = kit.to_file("#{Rails.root}/tmp/name.pdf")

     roy = Royarchive.new(:client_id => @contributor.client_id) 
     roy.pdf = thepdf
     roy.save!
     redirect_to :action => index
end 


来源:https://stackoverflow.com/questions/7269651/store-system-generated-pdf-on-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!