2012-02-27 19 views
7

ActionMailerに添付ファイルとしてprawn pdfをレンダリングするには?私はdelayed_jobを使用して理解していない、どうすればアクションメーラー(コントローラーではない)でpdfファイルをレンダリングできますか?私はどんなフォーマットを使うべきですか?Rails 3レンダリング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

0

私のソリューション:私はメール機能のためのブロックを書いていないとマルチパートメールが誤っていたので、

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

PDFが破損していました。

3

PRAWNのRailsCastに従った。既に何が言われているのか、同様に達成しようとしていたことを考えて、私は添付ファイル名を設定して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 
関連する問題