Generate PDF file from Rails view

642 views Asked by At

I have seen a lot of questions floating around on SO detailing how to display a PDF in the browser using prawn, but I want to create a PDF file to use as an attachment in an email.

Currently I am sending HTML formatted invoices to our merchants using the Rails ActionMailer. We have been requested to instead generate a PDF of the invoice and send that as an attachment so they can keep the files for their internal records.

I want to be able to use the same erb template I was using for sending emails (this is the crucial part) but instead output a PDF. Is this possible using Prawn (or anything else)?

1

There are 1 answers

0
tomasbasham On BEST ANSWER

I decided to use wicked_pdf in the end as was suggested in the comment on my question. I was able to use it as such

mail subject: "Order #{order.id}" do |format|
  format.text
    format.html do
      attachments["receipt #{Time.now}.pdf"] = WickedPdf.new.pdf_from_string(
        render_to_string pdf: 'receipt', template: 'order_mailer/order_receipt.html.erb'
      )
      render 'order_receipt'
    end
  end
end

This still renders out emails in HTML and text forms but also attaches a PDF to the email which uses the same template as the mailer