Rails 3 -Render PDF from view and attach to email

FattRyan picture FattRyan · Apr 23, 2011 · Viewed 14.6k times · Source

I have been using Wicked_pdf to render a view as a PDF and actionmailer to send emails, but I can't get them to work together. I want to attach a PDF version of a certain view to an email using actionmailer and send it out by clicking a link or a button. I have a link_to command that sends out an email. Here is my controller that gets the email generated:

def sendemail
 @user = User.find(params[:id])
 Sendpdf.send_report(@user).deliver
 redirect_to user_path(@user)
 flash[:notice] = 'Email has been sent!'
end  

Here is what I have in my actionmailer:

class Sendpdf < ActionMailer::Base
default :from => "[email protected]"

def send_report(user)
@user = user
  attachment "application/pdf" do |a|
  a.body = #Something should go here, maybe WickedPDF.new.something?
  a.filename = 'MyPDF'
end     
mail(:to => user.email, :subject => "awesome pdf, check it")
end

end

I have seen many questions and answers, most dealing with Prawn. It seems like there should be a simple answer to this. Can anyone help?

UPDATE I'm grateful for a suggestion to use as an alternative option in the answer below. However, I would really like to learn how to render a view as a PDF and attach it to my email. I am open to using something different like Prawn or anything else if I need to.

Answer

Unixmonkey picture Unixmonkey · Apr 28, 2011

2 good ways to do this the way you want:

1: Create the pdf in the controller, then send that to the email as a param.

# controller
def sendemail
  @user = User.find(params[:id])
  pdf = render_to_string :pdf => 'MyPDF'
  Sendpdf.send_report(@user, pdf).deliver
  redirect_to user_path(@user)
  flash[:notice] = 'Email has been sent!'
end

# mailer
def send_report(user, pdf)
  @user = user
  attachments['MyPDF.pdf'] = pdf
  mail(:to => user.email, :subject => "awesome pdf, check it")
end

2: Create the pdf in the mailer directly (a little more involved, but can be called from a model)

def send_report(user)
  @user = user
  mail(:to => user.email, :subject => "awesome pdf, check it") do |format|
    format.text # renders send_report.text.erb for body of email
    format.pdf do
      attachments['MyPDF.pdf'] = WickedPdf.new.pdf_from_string(
        render_to_string(:pdf => 'MyPDF',:template => 'reports/show.pdf.erb')
      )
    end
  end
end