How to specify layout when connecting PDF to email with Wicked PDF

I can't get the email to generate when I try to specify the layout for the pdf I want to attach to the email using Wicked PDF. This app is for rails 4.

When I use the following code, the application successfully sends an email with a pdf attachment, but without the desired styling:

def invoice_created(invoice_id)
  @invoice = Invoice.find(invoice_id)
  @subscription = Subscription.find(@invoice.subscription_id)
  attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
    render_to_string(:pdf => "invoice", :template => 'invoices/show.pdf.erb'))
  mail(to: 'you@example.com', subject: "Your Invoice is Ready")
end

      

But when I add the layout, nothing is generated.

def invoice_created(invoice_id)
  @invoice = Invoice.find(invoice_id)
  @subscription = Subscription.find(@invoice.subscription_id)
  attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
    render_to_string(:pdf => "invoice", 
                     :template => 'invoices/show.pdf.erb', 
                     :layout => 'pdf.html.erb'))
  mail(to: 'you@example.com', subject: "Your Invoice is Ready")
end

      

In my controller, I display the pdf in the browser and use the pdf.html.erb format correctly:

def show
  @invoice = current_account.invoices.find(params[:id])
  respond_to do |format|
    format.html
    format.pdf do
      render :pdf => 'file_name',
      :template => 'invoices/show.pdf.erb',
      :layout => 'pdf.html.erb'
    end
  end
end

      

I don't see any obvious errors in the dev log other than the generated email file.

I see the following, so it looks like it sees the layout, but doesn't display it.

Rendered invoices/show.pdf.erb within layouts/pdf.html.erb (13.7ms)

      

There might be a problem with conflicting layouts?

If I try to create multiple emails with the specified layout, remove the layout code from the mailer, restart the server, request a new email, and then the sent emails that I previously requested have been sent.

I tried adding

:show_as_html => params[:debug].present?

      

for the mailer to see if it shed some light, but that also didn't cause the letter to be sent.

+3


source to share


1 answer


The problem code was in pdf format:

<%= csrf_meta_tags %>

      

Not sure why I didn't get any error messages in my application. I have my application installed to display errors with gem 'better_errors'

that did not display any errors. I created a new app to play with wicked_pdf but didn't add good_errors to the gem file.

Now I got the following error message:



undefined method `protect_against_forgery?'

      

Once this line was removed from the file layouts/pdf/html.erb

, the application linked the styled pdf file correctly.

Here's a link to the wicked_pdf example I used to find a solution: https://github.com/stevejc/WickedPDF-Example

+3


source







All Articles