If you are using wicked_pdf and try to generate pdf outside of controller (i.e. in a cron job) you can do it this way (raild 4.1 +):
# app/renderers/pdf_renderer.rb
class PdfRenderer < ActionController::Metal
include ActionView::ViewPaths
include AbstractController::Rendering
include AbstractController::Helpers
include ActionController::Helpers
include ActionView::Rendering
include ActionView::Layouts
include ActionController::Rendering
include ActionController::Renderers
include ActionController::Renderers::All
append_view_path "app/views"
View = Struct.new(:layout, :template, :locals)
def render_pdf(view)
wicked = WickedPdf.new
pdf_string = render_to_string(template: view.template, layout: view.layout, locals: view.locals)
# Make a PDF in memory
pdf_file = wicked.pdf_from_string(pdf_string, pdf: "pdf_name",
page_size: 'A4',
wkhtmltopdf: ENV['WKHTMLTOPDF_EXECUTABLE_PATH'],
margin: { top: '0.5in', bottom: '1in', left: '0.5in', right: '0.5in'}
)
# Write it to tempfile
tempfile = Tempfile.new(['document', '.pdf'], Rails.root.join('tmp'))
tempfile.binmode
tempfile.write pdf_file
tempfile.close
tempfile
end
end
and call this method:
renderer = PdfRenderer.new
pdf_view = PdfRenderer::View.new.tap do |v|
v.template = "postal/#{template_file}.pdf.erb"
v.layout = 'layouts/layout.pdf.erb'
v.locals = {:user=> @user, :other_stuff => @details}
end
temp_pdf = renderer.render_pdf pdf_view
now you can use temp_pdf.path
to do whatever you want with this file (i.e. send email)
you can read more about this way here: http://blog.arkency.com/2014/03/pdf-in-rails-without-controllers/