2011-02-17 33 views
20

我正在使用Prawn和Prawnto向用戶顯示基於PDF的報告,但在某些情況下,我還想將PDF作爲附件保存到我的某個模型中。我爲所有附件使用回形針。有沒有人有任何建議如何做到這一點?將蝦PDF保存爲回形針附件?

謝謝!

回答

8

它應該工作,如果你只是通過文件引用到該PDF到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 
+0

謝謝它適合我。 – tjeden

25

使用prawnto時,您需要評估.pdf.prawn模板中的變量。 第二步是模仿回形針的真實文件。

  1. 生成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. 保存PDF用回形針:

    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! 
    

希望這有助於。

+0

我發現這非常有助於從模型方法生成pdf。我遇到的一個錯誤是,如果您的prawnto模板使用pdf.method_name樣式,則必須命名Prawn :: Document.new「pdf」的輸出。謝謝! – Unixmonkey

2

我得到了它沒有實例的eval合作,通過扭轉它的其他方式:生成PDF在模型中,呈現在你控制器

在模型:

def generate_pdf 
    Prawn::Document.new(:page_size => 'A4', :top_margin => 0, :left_margin => 0) do |pdf| 
     <your pdf code here> 
     <copy paste from your template> 
    end.render 
    end 

你就可以發送它作爲郵件附件:

attachment = generate_pdf 
mail = Notifier.send_pdf(attachment) 
mail.deliver 

,或者使之在你的控制你的瀏覽器窗口:

send_data your_model.generate_pdf, :type => "application/pdf", :disposition => 'inline' 
+0

^這是關於如何使用普通的蝦生成例程並呈現屏幕或電子郵件的完美答案。謝謝! – Jetblackstar

1

這爲我工作

pdf = Prawn::Document.new(:page_size => "LETTER", :page_layout => :landscape) 
pdf.render_file File.join(Rails.root, "app/pdfs", "x.pdf") 
current_user.certificate = File.open("#{Rails.root}/app/pdfs/x.pdf") 
current_user.save! 

哪裏certificate是我的紙夾附件保存爲模型:

class User < ActiveRecord::Base 
    has_attached_file :certificate 
0

@Adam阿爾布雷希特,你將被保存的圖像作爲附件,但爲保存pdf作爲附件,您需要添加一個驗證 -

**** validates_att achment:document,content_type:{content_type:'application/pdf'} ****