7

How to render prawn pdf as attachment in ActionMailer? I use delayed_job and don't understand, how could I render pdf-file in action mailer (not in controller). What format should I use?

3 Answers 3

7

You just need to tell Prawn to render the PDF to a string, and then add that as an attachment to the email. See the ActionMailer docs for details on attachments.

Here's an example:

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
1
  • I already have views/invoices/show.pdf.prawn. InvoicesController renders it successfully. I tried to render it using render_to_string in mailer and got corrupt PDF. How to render this existing view file? May be I need to specify :type or format for render_to_string.
    – maxs
    Feb 28, 2012 at 8:22
3

I followed the RailsCasts for PRAWN. Taken what has already been said and what I was trying to similarly accomplish, I set the attachment name and then created the 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
0

My solution:

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

PDF was corrupted because I didn't write block for mail function and multi-part email was incorrect.

1
  • This solution doesn't work in Rails 5.x I get undefined method response' for #<PicksheetMailer:0x007fcfa506f258> Did you mean? response_body' when I tried to render a prawn template using ` attachments["customer_order_#{@order.order_number}.pdf"] = render_to_string('picksheet/send_picksheet.pdf', :type => :prawn)` So it seems that prawn is expecting to write to a response which doesn't exist inside ActionMailer
    – John Small
    Aug 28, 2018 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.