Rails 3 ActionMailer and Wicked_PDF

前端 未结 3 1533
后悔当初
后悔当初 2020-12-08 15:21

I\'m trying to generate emails with rendered PDF attachements using ActionMailer and wicked_pdf.

On my site, I\'m using already both wicked_pdf and actionmailer se

相关标签:
3条回答
  • 2020-12-08 15:42

    Heres' how I fixed this issue:

    1. Removed wicked_pdf
    2. Installed prawn (https://github.com/sandal/prawn/wiki/Using-Prawn-in-Rails)

    While Prawn is/was a bit more cumbersome in laying out a document, it can easily sling around mail attachments...

    0 讨论(0)
  • 2020-12-08 15:48

    I used of Unixmonkey's solutions above, but then when I upgraded to rails 3.1.rc4 setting the @lookup_context instance variable no longer worked. Perhaps there's another way to achieve the same clearing of the lookup context, but for now, setting the attachment in the mail block works fine like so:

      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
    
    0 讨论(0)
  • 2020-12-08 16:01

    WickedPDF can render to a file just fine to attach to an email or save to the filesystem.

    Your method above won't work for you because generate_pdf is a method on the mailer, that returns a mail object (not the PDF you wanted)

    Also, there is a bug in ActionMailer that causes the message to be malformed if you try to call render in the method itself

    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

    There are 2 ways you can make this work,

    The first is to use the hack described in the first article above:

    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
    

    Or, you can set the attachment in a block like so:

    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 讨论(0)
提交回复
热议问题