Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a Prawn PDF as a Paperclip attachment?

Tags:

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!

like image 362
Adam Albrecht Avatar asked Feb 17 '11 21:02

Adam Albrecht


2 Answers

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.

  1. 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 
  2. 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.

like image 73
David Barlow Avatar answered Sep 18 '22 21:09

David Barlow


It should work if you just pass a File reference to that PDF to Paperclip.

require 'prawn' pdf = Prawn::Document.new pdf.text("Prawn Rocks") pdf.render_file('/path/to/prawn.pdf')  pdf_file = File.open('/path/to/prawn.pdf')  # assuming your Paperclip association is named "pdf_attachment" my_model.pdf_attachment = pdf_file 
like image 23
jemminger Avatar answered Sep 17 '22 21:09

jemminger