Save a Prawn PDF as a Paperclip attachment?

后端 未结 5 1179
悲&欢浪女
悲&欢浪女 2021-02-04 01:24

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 usi

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 02:02

    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.

提交回复
热议问题