首页 文章

Rails 3 ActionMailer和Wicked_PDF

提问于
浏览
22

我正在尝试使用ActionMailer和wicked_pdf生成带有渲染PDF附件的电子邮件 .

在我的网站上,我已经分别使用了wicked_pdf和actionmailer . 我可以使用wicked_pdf在Web应用程序中提供pdf,并且可以使用ActionMailer发送邮件,但是我无法将呈现的pdf内容附加到ActionMailer(针对内容进行编辑):

class UserMailer < ActionMailer::Base
  default :from => "webadmin@mydomain.com"

  def generate_pdf(invoice)
    render :pdf => "test.pdf",
     :template => 'invoices/show.pdf.erb',
     :layout => 'pdf.html'
  end

  def email_invoice(invoice)
    @invoice = invoice
    attachments["invoice.pdf"] = {:mime_type => 'application/pdf',
                                  :encoding => 'Base64',
                                  :content => generate_pdf(@invoice)}
    mail :subject => "Your Invoice", :to => invoice.customer.email
  end
end

使用Railscasts 206(Rails 3中的Action Mailer)作为指南,只有在我不尝试添加渲染的附件时,我才能发送包含我所需的丰富内容的电子邮件 .

如果我尝试添加附件(如上所示),我会看到一个看起来正确大小的附件,只有附件的名称没有按预期发现,也不能作为pdf读取 . 除此之外,我的电子邮件内容丢失了......

有没有人在使用Rails 3.0动态渲染PDF时有使用ActionMailer的经验?

提前致谢! - 担

3 回答

  • 30

    WickedPDF可以渲染到一个文件,可以附加到电子邮件或保存到文件系统 .

    上面的方法不适合你,因为 generate_pdf 是邮件程序上的一个方法,它返回一个邮件对象(不是你想要的PDF)

    此外,如果您尝试在方法本身中调用render,则ActionMailer中存在导致消息格式错误的错误

    http://chopmode.wordpress.com/2011/03/25/render_to_string-causes-subsequent-mail-rendering-to-fail/

    https://rails.lighthouseapp.com/projects/8994/tickets/6623-render_to_string-in-mailer-causes-subsequent-render-to-fail

    有两种方法可以使这项工作,

    第一个是使用上面第一篇文章中描述的hack:

    def email_invoice(invoice)
      @invoice = invoice
      attachments["invoice.pdf"] = WickedPdf.new.pdf_from_string(
        render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
      )
      self.instance_variable_set(:@lookup_context, nil)
      mail :subject => "Your Invoice", :to => invoice.customer.email
    end
    

    或者,您可以在块中设置附件,如下所示:

    def email_invoice(invoice)
      @invoice = invoice
      mail(:subject => 'Your Invoice', :to => invoice.customer.email) do |format|
        format.text
        format.pdf do
          attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
            render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
          )
        end
      end
    end
    
  • 0

    我使用上面的Unixmonkey解决方案,但是当我升级到rails 3.1.rc4时,设置@lookup_context实例变量不再有效 . 也许还有另一种方法可以实现查找上下文的相同清除,但是现在,在邮件块中设置附件可以正常工作:

    def results_email(participant, program)
        mail(:to => participant.email,
             :subject => "my subject") do |format|
          format.text
          format.html
          format.pdf do
            attachments['trust_quotient_results.pdf'] = WickedPdf.new.pdf_from_string(
              render_to_string :pdf => "results",
                   :template => '/test_sessions/results.pdf.erb',
                   :layout => 'pdf.html')
          end
       end
      end
    
  • 4

    继承人'我是如何解决这个问题的:

    虽然Prawn在布置文档时有点麻烦,但它可以很容易地围绕邮件附件...

相关问题