如果您使用 wicked_pdf 并尝试在控制器之外生成 pdf(即在 cron 作业中),您可以这样做(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
并调用此方法:
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
现在你可以用temp_pdf.path
这个文件做任何你想做的事情(即发送电子邮件)
你可以在这里阅读更多关于这种方式的信息:http: //blog.arkency.com/2014/03/pdf-in-rails-without-controllers/