1

I'm using rails 3.0 and PDFKit. SASS and HAML but I don't have the asset pipeline implemented yet.

If I make a call from a controller I can generate perfect styled pdf with images, calling PDFKit.new passing render_to_string :show. But if I do the same through a rake task, my PDF is generated without styles, and image_tag helper throws an error like this:

can't convert nil into String

Surely, I'm doing something wrong in the rake task... but everything works in the controller... What I'm missing? Should I include something in the rake task? or maybe use another view with inline styles and absolute paths? the calls are these:

CONTROLLER VERSION

def generate_html_invoice
  render_to_string :show, layout: 'mypdflayout'
end

mypdf = PDFKit.new html_generator

RAKE TASK VERSION

def generate_html_invoice
  invoice_view = ActionView::Base.new(MyWeb::Application.config.paths["app/views"].first)
  invoice_view.assign({ ....... various params here})
  html_invoice = invoice_view.render(template: "invoices/show", layout: 'mypdflayout')
return html_invoice

mypdf = PDFKit.new html_generator

The same error is thrown by image_tag helper and stylesheet_link_tag helper

An alternative way could be instantiate the controller in the rake task but.. is it possible? and, is it a good practice?

jonnyjava.net
  • 912
  • 7
  • 23

1 Answers1

1

I couldn't find any decent solution to this, but I tried the following techniques:

  • QUICK AND DIRTY

change the view using %link and %img HAML tags instead the helpers, using the absolute path to the files.

  • SLOW BUT ELEGANT

In the rake task, call the controller to receive the view url and give it to PDFKit in this way

url = "#{(Rails.env.production? ? 'http://www.example.com' : 'http://localhost')}/invoce/#{invoice.id}"
path_to_pdf = "root/......./mypdf.pdf"
invoce_page = PDFKit.new url
invoce_page.to_file(path_to_pdf)

This one is the solution I choose. I know, it's a little dumb: the controller calls a rake task which calls the controller again... And it makes a lot of http request to the server. But in this way I can have a underground process to generate PDF invoices without waiting for the response.

I think I don't have to worry about overcharging the server because the request will be queued normally.

jonnyjava.net
  • 912
  • 7
  • 23