Save a Prawn PDF as a Paperclip attachment?

Adam Albrecht picture Adam Albrecht · Feb 17, 2011 · Viewed 8.9k times · Source

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!

Answer

David Barlow picture David Barlow · Feb 25, 2011

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.