【问题标题】:Rails 3 Render Prawn pdf in ActionMailerRails 3 在 ActionMailer 中渲染虾 pdf
【发布时间】:2012-02-27 15:55:37
【问题描述】:

如何在 ActionMailer 中将虾 pdf 渲染为附件?我使用delayed_job 并且不明白,我怎么能在action mailer 中渲染pdf 文件(不在控制器中)。我应该使用什么格式?

【问题讨论】:

    标签: ruby-on-rails actionmailer prawn


    【解决方案1】:

    您只需要告诉 Prawn 将 PDF 呈现为字符串,然后将其作为附件添加到电子邮件中。有关附件的详细信息,请参阅ActionMailer docs

    这是一个例子:

    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
    

    【讨论】:

    • 我已经有意见/发票/show.pdf.prawn。 InvoicesController 成功呈现它。我尝试在邮件程序中使用 render_to_string 渲染它并得到损坏的 PDF。如何渲染这个现有的视图文件?可能我需要为 render_to_string 指定 :type 或 format。
    【解决方案2】:

    我关注了PRAWN 的 RailsCasts。考虑到已经说过的内容以及我试图类似完成的内容,我设置了附件名称,然后创建了 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
    

    【讨论】:

      【解决方案3】:

      我的解决方案:

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

      PDF 已损坏,因为我没有为邮件功能编写块并且多部分电子邮件不正确。

      【讨论】:

      • 这个解决方案在 Rails 5.x 中不起作用我得到了undefined method response' for #<0x007fcfa506f258>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多