2
votes

I am using wicked-pdf to simplify generating pdf invoices in my Rails 5 application. I have two actions making use of the pdf functionality of wicked-pdf. The first action generates the pdf and renders it in a new browser window. The second method attaches the pdf to an email.

Both of these actions work just fine. The issue comes in when I set my pdf mailer action to 'deliver_later' using ActiveJob/Sidekiq. When I add 'deliver_later' I am presented with a error stating:

"\xFE" from ASCII-8BIT to UTF-8

This error does not happen if I use the "deliver_now" command. Using "deliver_now" send the email and attaches the PDF correctly.

Here is some of my code for the mailing action, mailer and job:

invoices_controller.rb

...
def create
  respond_to do |format|
    format.html do
      pdf = render_to_string( pdf: @order.ruling_invoice,
                          template: "orders/invoices/show.pdf.haml",
                          encoding: "utf8",
                          locals: { order: @order.decorate}
                        )
      SendInvoiceMailJob.new.perform( @order, pdf, @order.token )
      redirect_to order_url(id: @order.id, subdomain: current_company.slug),     notice: "This invoice has been emailed."
    end
  end
end
...

send_invoice_mail_job.rb

...
def perform( order, pdf, order_token )
  InvoiceMailer.send_invoice(order, pdf, order_token).deliver_later
end
...

invoice_mailer.rb

...
def send_invoice( order, pdf_invoice , invoice_token)
    @order = order
    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end
...

Why would this code work using "deliver_now" in send_invoice_mail_job.rb but it doesn't work using "deliver_later" ?

2
Did you find the solution? I have the same problemmoondaisy
@moondaisy I did. I would have to go and look at around at what I did though as I can't remember clearlyHermannHH
If you happen to have time, please post it as the answer here :) I haven't find any other questions referring to this or examples of how to do itmoondaisy

2 Answers

0
votes

You need to move the PDF compiling from outside of your mailer job to inside it. So in your controller, you can do:

SendInvoiceMailJob.new.perform(@order, @order.token)

Then in your mailer job you can do:

def send_invoice(order, invoice_token)
    @order = order

    pdf = render_to_string(
      pdf: @order.ruling_invoice,
      template: "orders/invoices/show.pdf.haml",
      locals: { order: @order.decorate }
    )                        )

    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end

That way you're not passing the PDF binary into the jobs queue.