Set dynamic header and footer data on PDF generation from rails (Grover gem)

2.6k Views Asked by At

Using this gem so I can run NodeJS Puppeteer from Rails:

https://github.com/Studiosity/grover

I'm trying to render different reports in HTML to a PDF file so the users can download them.

When doing this through a middleware, I have the config/initializers/grover.rb:

Grover.configure do |config|
  view = ActionView::Base.new(ActionController::Base.view_paths, {})

  header_template = view.render(:template => "pdf/_header", :layout => false, :spa => spa, :codigo => codigo)
  footer_template = view.render(:template => "pdf/_footer", :layout => false, :doctitle => @doctitle, :spa => spa, :codigo => codigo, :page => page, :topage => topage)

  config.options = {
    display_url: Settings.corporativo,
    format: 'A4',
    margin: {
      top: '0.8in',
      bottom: '0.65in',
      right: '0.45in',
      left: '0.5in'
    },
    prefer_css_page_size: true, #Doesn't seem to work. Still the margins set here are the ones that rule.
    display_header_footer: true,
    header_template: header_template,
    footer_template: footer_template,
    print_background: true,
    emulate_media: 'print',
    cache: false,
    timeout: 0
  }
end

Do you have an idea of how I could pass dynamic parameters to these templates? Because, setting this templates in initializing time makes them static as far as I can tell...

Here, one of my templates _footer.html.haml:

%footer{:style => "display:flex; justify-content: space-between; font-size:6px !important; width: calc(100% - 0.75in); margin: 0 auto;"}
  %span.title
  #description{:style => "text-align:center;font-size: 6px;"}
    - if [email protected]?
      = raw t('pdfkit.footer_E')
    - else
      = raw t('pdfkit.footer')
  .pageContainer
    %span.pageNumber
    = "/"
    %span.totalPages
1

There are 1 best solutions below

4
rmartrenado On

I didn't find any way to do it.

I ended up using the to_pdf method and converting the HTML obtained in the controller. Then, all I had to take care of is making sure that the mime type that you are returning to the request is correct:

    html = render_to_string(:action => "pdf.html.haml", :layout => 'layout_pdf')
    header_template = render_to_string(:template => "pdf/_header", :layout => false, :spa => spa, :codigo => codigo)
    footer_template = render_to_string(:template => "pdf/_footer", :layout => false, :doctitle => @doctitle, :spa => spa, :codigo => codigo, :page => page, :topage => topage)

    grover = Grover.new(html,
      header_template: header_template,
      footer_template: footer_template
    )

    pdf = grover.to_pdf

    send_data pdf, type: Mime::PDF, disposition: 'inline'