Rails 3 Render Prawn pdf in ActionMailer

前端 未结 3 1357
青春惊慌失措
青春惊慌失措 2021-01-05 07:10

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

3条回答
  •  盖世英雄少女心
    2021-01-05 07:38

    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
    

提交回复
热议问题