Skip to main content

How to generate PDF based on search using prawn in ruby on rails

Gems / Libraries • Asked by Francisco Quinones

So Chris im using prawn pdf in my app.
Now im adding some search form to filter by date range. All works fine and I get my filter table on my index. my problem is with prawn that wont hold the filter records

my form filter range

        <%= form_tag({controller: "accidents", action: "index"}, {:class => 'navbar-form navbar-left', method: "get"}) do %>
              <%= text_field_tag :from_date, params[:from_date], class: "form-control", placeholder: "Fecha Inicial" %>
              <%= text_field_tag :to_date, params[:to_date], class: "form-control", placeholder: "Fecha Final" %>
              <%= submit_tag 'Buscar', class: "btn btn-primary" %>
        <% end %>

my controller code

  def index
    if params[:from_date] && params[:to_date].present?
       from_date = Date.strptime(params[:from_date], "%d/%m/%Y")
       to_date = Date.strptime(params[:to_date], "%d/%m/%Y") + 1.day
       @accidents = @project.accidents.sorting.where(:date => from_date..to_date)
       .paginate(:page => params[:accidents], :per_page => 10)
    else
        @accidents = @project.accidents.sorting.paginate(:page => params[:accidents], :per_page => 10)
    end
    respond_to do |format|
        format.html
        # format.csv { send_data  @accidents.to_csv}
        format.pdf do
          pdf = AccidentsReportPdf.new(@accidents,@project)
          send_data pdf.render,filename: "accidente_reporte_#{@project.name}.pdf",
                              type: "application/pdf",
                              disposition: "inline"
      end
    end
  end

This my index filter with a range of date

http://companydemo.lvh.me:3000/projects/conroy-schamberger-and-crooks/accidents?utf8=%E2%9C%93&from_date=01%2F01%2F2016&to_date=31%2F01%2F2016&commit=Buscar

when I go to see the pdf version

<%= link_to Report, project_incidents_path(format: "pdf"), :class=> "btn" %>

I get

  http://companydemo.lvh.me:3000/projects/conroy-schamberger-and-crooks/accidents.pdf

maybe I need to past the dates to the link_to pdf. If so how is the right way to pass that data.


I found that this works

<%= link_to Report, project_incidents_path(params.merge(format: "pdf")), :class=> "btn" %>

I get this

http://companydemo.lvh.me:3000/projects/conroy-schamberger-and-crooks/incidents?action=index&commit=Buscar&controller=incidents&format=pdf&from_date=01%2F01%2F2016&project_id=conroy-schamberger-and-crooks&to_date=31%2F01%2F2016&utf8=%E2%9C%93

but I dont know if is the best way.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.