2012-02-27 29 views
7

Làm cách nào để hiển thị tệp prawn pdf dưới dạng tệp đính kèm trong ActionMailer? Tôi sử dụng delay_job và không hiểu, làm thế nào tôi có thể làm cho tập tin pdf trong hành động gửi thư (không phải trong bộ điều khiển). Tôi nên sử dụng định dạng nào?Rails 3 Vẽ pdf tôm trong ActionMailer

Trả lời

7

Bạn chỉ cần yêu cầu Prawn hiển thị tệp PDF thành chuỗi và sau đó thêm tệp đó dưới dạng tệp đính kèm vào email. Xem ActionMailer docs để biết chi tiết về tệp đính kèm.

Dưới đây là một ví dụ:

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

Tôi đã có views/hóa đơn/show.pdf.prawn. InvoicesController hiển thị thành công. Tôi đã cố gắng để render nó bằng cách sử dụng render_to_string trong mailer và đã bị hỏng PDF. Cách hiển thị tệp xem hiện tại này? Có thể tôi cần phải chỉ định: loại hoặc định dạng cho render_to_string. – maxs

0

Giải pháp của tôi:

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

PDF đã bị hỏng bởi vì tôi đã không viết block cho chức năng mail và email đa phần là không chính xác.

3

Tôi đã theo dõi RailsCasts cho PRAWN. Lấy những gì đã được nói và những gì tôi đã cố gắng để thực hiện tương tự, tôi đặt tên tập tin đính kèm và sau đó tạo ra 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 
Các vấn đề liên quan