Search code examples
ruby-on-railsruby-on-rails-4pdf-generationwkhtmltopdfwicked-pdf

footers html content is not getting printed in wicked_pdf + rails


I am using wicked_pdf to generate pdf for my rails application. I am trying to render a dynamic html content at the footer of my generated pdf.

I have implemented following code in controller:

 #app/controllers/receipts_controller.rb
  def generate_receipt
    html = render_to_string(:action => 'print_receipt', 
            :layout => false)       

    pdf = WickedPdf.new.pdf_from_string(html,
      :encoding => 'UTF-8',
      :page_size => 'A4',
      :orientation => 'Portrait',
      #:footer =>  { :content => "This is my footer content."},
      :footer => { :html => { :template => 'footer.html.erb' } } )
      send_data(pdf, :filename  => get_file_name, :disposition => 'attachment')
  end

If I use just the static content(check the above commented section) then it works as intended. But it's unable to load the footer content from the provided template location.

my footer resides at :

#app/views/receipts/footer.html.erb
 <div class='rec-foot'> This is my footer content (this is dynamic) </div>

This is how I have my print template:

#app/views/receipts/print_receipt.html.erb
  <htmL>
    <head>
      <%= wicked_pdf_stylesheet_link_tag "wicked_pdf" %>
    </head>
    <body>
      <!--- my pdf page content goes here -->
     </body>
   </html> 



# app/assets/stylesheets/wicked_pdf.css
   .rec-foot{
      font-weight: bold;
      text-align: center;
    }

Issue : footer section is not getting rendered for the dynamic html content.


Solution

  • I believe :template won't work for you because you are using pdf_from_string (source: the commented-out lines near footer notes.)

    We went with :content by doing something like this in our app/models/pdf_builder.rb:

    :footer: {
      content: { footer_html }
    }
    

    Then defined:

    def footer_html
      ERB.new(pdf_template).result(binding)
    end
    
    def pdf_template
      File.read("full/path/of/your/file.html.erb")
    end
    

    We initialize in app/models/pdf_builder.rb with any of the info we need dynamically populating in /app/views/pdf_footer.en.html.erb