2012-02-27 72 views
7

如何在ActionMailer中將prawn pdf作爲附件渲染?我使用delayed_job並且不明白,我如何在行動郵件程序中渲染pdf文件(不在控制器中)。我應該使用什麼格式?Rails 3 Render Prawn pdf in ActionMailer

回答

7

您只需要告訴Prawn將PDF渲染爲字符串,然後將其添加爲電子郵件的附件。有關附件的詳細信息,請參閱ActionMailer docs

下面是一個例子:

class ReportPdf 
    def initialize(report) 
    @report = report 
    end 

    def render 
    doc = Prawn::Document.new 

    # Draw some stuff... 
    doc.draw_text @report.title, :at => [100, 100], :size => 32 

    # Return the PDF, rendered to a string 
    doc.render 
    end 
end 

class MyPdfMailer < ActionMailer::Base 
    def report(report_id, recipient_email) 
    report = Report.find(report_id) 

    report_pdf_view = ReportPdf.new(report) 

    report_pdf_content = report_pdf_view.render() 

    attachments['report.pdf'] = { 
     mime_type: 'application/pdf', 
     content: report_pdf_content 
    } 
    mail(:to => recipient_email, :subject => "Your report is attached") 
    end 
end 
+0

我已經有意見/發票/ show.pdf.prawn。 InvoicesController成功呈現它。我試圖在郵件程序中使用render_to_string來渲染它,並得到了損壞的PDF。如何渲染這個現有的視圖文件?可能是我需要指定:render_to_string的類型或格式。 – maxs 2012-02-28 08:22:25

0

我的解決辦法:

render_to_string('invoices/show.pdf', :type => :prawn) 

PDF被損壞,因爲我沒有寫的郵件功能和多部分郵件阻塞是不正確的。

3

我跟着RailsCasts的PRAWN。採取了已經說過的和我試圖類似完成的事情之後,我設置了附件名稱,然後創建了PDF。

InvoiceMailer:

def invoice_email(invoice) 
    @invoice = invoice 
    @user = @invoice.user 
    attachments["#{@invoice.id}.pdf"] = InvoicePdf.new(@invoice, view_context).render 
    mail(:to => @invoice.user.email, 
     :subject => "Invoice # #{@invoice.id}") 
    end