Rails 3 -Render PDF from view and attach to email

我只是一个虾纸丫 提交于 2019-11-30 03:12:34
Jatin Ganhotra

There are 2 ways for it.

  1. Either, you want the pdf to be embedded in the email you are sending, so that when the user downloads the pdf from the email, there is no request to the render new pdf action for your respective controller.
    I don't know how to do this efficiently because I have never done this before.

  2. Or, you just provide a link to the pdf in your email and when the user clicks on it, now the action for creating the pdf is called, and then the user can download it.
    This way, if there is a lot of burden on the server for the downloading of the pdf's, you can redirect these requests somewhere else. In short, there is a huge scope for efficiency.

A sample code for the 2nd method(code provided was written by using PDFkit, so change accordingly):

class PdfsController < ApplicationController
  def pdf
    respond_to do |format|
      format.pdf { render :text => wickedPDF.new( Pdf.find(params[:id]).content ).to_pdf }
    end
  end
...
end

Replace the Pdf.find(params[:id]).content as per your choice, and the to_pdf method, as per wickedPDF.

Then, you can simply pass the link for the pdf download in your email like this

<%= link_to "Download", pdf_pdf_path(pdf, :format => "pdf") %>

or whatever suits as per wickedPDF.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!