6

I try to convert rails views into pdf with the gem wicked_pdf. But when I do a render_to_string like this

ActionController::Base.new.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')

Methods like user_path don't work and return undefined method error... (note that the page work properly if I render it in html) If someone can help me !

guhurak
  • 143
  • 8

3 Answers3

5

You can include helpers by using the following method

ac = ActionController::Base.new
ac.view_context_class.include(ActionView::Helpers, ApplicationHelper)
ac.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')
Vikas Kumar
  • 2,978
  • 3
  • 14
  • 24
4

Unfortunately, using render_to_string will not give you access to Rails URL helpers. One workaround is to include them directly in the locals that you pass into the PDF template using something like url: Rails.application.routes.url_helpers:

ActionController::Base.new.render_to_string(
  template: "templates/pdf_meteo.html.erb",
  locals: {url: Rails.application.routes.url_helpers, communaute_meteo_id: id}
  layout: 'pdf'
)

And then inside of your PDF template you would call them with:

url.user_path

Keep in mind that by default the _path URL helpers will be relative, and not absolute paths. You can instead use the _url version of the helpers and set the host for them in a few different ways. You can configure them globally for your entire app:

# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'

or set them individually on each helper inside of your PDF template:

url.user_url(host: 'www.mysite.com')

Hope that gets you what you need!

calebkm
  • 1,013
  • 4
  • 17
1

Simplest way is to use regular rails rendering flow - with view file your_action_name.pdf.erb, trick is in overriding formats for partials:

<%= render partial:"some_partial", formats:[:html] %>

Also you can run render_to_string in context of your controller to have helpers (because ActionController::Base knows nothing about your app)

Vasfed
  • 18,013
  • 10
  • 47
  • 53