I'm using Prawn and Prawnto to display a PDF-based reports to the user, but in some circumstances, I'd also like to save the PDF as an attachment to one of my models. I'm using Paperclip for all of my attachments. Does anyone have any suggestions on how to do this?
Thanks!
When using prawnto you will need to eval the variables in the .pdf.prawn template. Second step is to mimic a real file for paperclip.
Generating the PDF:
#find the prawwnto template you want
template = File.read("#{RAILS_ROOT}/app/views/reports/your_report.pdf.prawn")
pdf = Prawn::Document.new(:page_size => 'A4', :your_options => :etc)
pdf.instance_eval do
@report = find_report #put here, all local variables that the pdf template needs
eval(template) #this evaluates the template with your variables
end
attachment = pdf.render
Save PDF with paperclip:
file = StringIO.new(attachment) #mimic a real upload file
file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
file.original_filename = "your_report.pdf"
file.content_type = "application/pdf"
#now just use the file object to save to the Paperclip association.
# assuming your Paperclip association is named "pdf_report"
@report_store.pdf_report = file
@report_store.save!
Hope this helps.