Shruthi R Shruthi R - 3 months ago 81
Ruby Question

Rails 4 - Wicked pdf file send via email

In rails 4, I am using

gem 'wicked_pdf', '1.0.3'
and
gem 'wkhtmltopdf-binary', '0.9.9.3'
for pdf generation. I am downloading it as a file,

respond_to do |format|
format.html
format.pdf do
render :pdf => "#{@user.id}_file",
:disposition => "attachment",
:save_to_file => Rails.root.join('public/download_pdfs', "#{@user.id}_file.pdf"),
:layout => false
end
end


Here, I am sending this file via mail by adding this line in controller
Email.deliver_sample_file_mail(@user, "#{Rails.root}/public/download_pdfs/#{@user.id}_file.pdf")


In mailer,

def send_invoice_pdf_mail(user, file_path)
filename = file_path.split("/").last
attachments["#{filename}"] = File.read(file_path)
mail(:to =>user.email, :subject => "File has been sent") do |format|
format.html { render :partial =>"/emails/users/sample", :locals=>{:user=>user}, :layout=>"email"}
end
end


Now the issue is both download file and email send is happening together.

How can I avoid file download feature? And how can I generate
.pdf
file so that it should send only to an email id?

Answer

You can save file as below without download

pdf = render_to_string pdf: "#{@user.id}_file", encoding: "UTF-8"

# then save to a file
save_path = Rails.root.join('public/download_pdfs','#{@user.id}_file.pdf')
File.open(save_path, 'wb') do |file|
  file << pdf
end

Hope, this will Help you.