What is the correct way to render_to_string in wicked pdf?

user1323136 picture user1323136 · Apr 12, 2013 · Viewed 7.3k times · Source

This is what the documentation of wicked pdf specifies:

WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "pdf_file.pdf", :template => 'templates/pdf.html.erb', :layout => 'pdfs/layout_pdf'), 
:footer => {:content => render_to_string({:template => 'templates/pdf_footer.html.erb', :layout => 'pdfs/layout_pdf'})}
)   

What i get is ActionView::MissingTemplate Even though i have pdf.html.erb in directory. I use a gen_pdf method in the application controller and an equivalent pdf.html.erb in the views/application folder. What am i missing.

Answer

Joshua Pinter picture Joshua Pinter · Aug 5, 2015

Don't Use template.

I ran into the same problem as you. You have to render your PDF quite differently when you're doing it in a Controller action as opposed to a Mailer or something else.

First off, using template won't work. There's some other nuances but here is my implementation you can build off of:

notification_mailer.rb

def export

  header_html = render_to_string( partial: 'exports/header.pdf.erb', 
                                  locals:  { report_title: 'Emissions Export' } )

  body_html   = render_to_string( partial: "exports/show.pdf.erb" )

  footer_html = render_to_string( partial: 'exports/footer.pdf.erb' )

  @pdf = WickedPdf.new.pdf_from_string( body_html,
                                        orientation: 'Landscape',
                                        margin: { bottom: 20, top: 30 },
                                        header: { content: header_html },
                                        footer: { content: footer_html } )

  # Attach to email as attachment.
  attachments["Export.pdf"] = @pdf

  # Send email. Attachment assigned above will automatically be included.
  mail( { subject: 'Export PDF', to: '[email protected]' } )

end