0

What I want to do is, generate a PDF file from my current page. (HTML)

I call a controller function which generates my page, it fetches data from database and so on.

Now I want a button which saves the current rendered page as a PDF file on the visitors machine. How can I do that?

If I use your code like this:

respond_to do |format|
  format.html { render :template => "user/settings" }
  format.pdf {
    kit = PDFKit.new('http://google.com')
    kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css"
    send_data(kit.to_pdf, :filename=>"sdasd.pdf",
              :type => 'application/pdf', :disposition => 'inline')
  }

end

and reload the page ... nothing gonna be downloaded as a pdf ... why?

Felix
  • 5,452
  • 12
  • 68
  • 163

1 Answers1

1

You can create a similar template for pdf of your current page. Then you can use pdfkit gem.

Add this gems to your gemfile:

gem "pdfkit"
gem "wkhtmltopdf-binary"

Add something like this at your controller:

  def show
    @user= User.find(params[:id])
    respond_to do |format|
      format.html { render :template => "users/show" }
      format.pdf {
        html = render_to_string(:layout => false , :action => "show.pdf.erb") # your view erb files goes to :action 

        kit = PDFKit.new(html)
        kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css"
        send_data(kit.to_pdf, :filename=>"#{@user.id}.pdf",
          :type => 'application/pdf', :disposition => 'inline')
    }

    end

  end

Now you can download pdf by adding .pdf to your controller route. eg: controller/routes/path/1.pdf

Or if you don't like it you can do

kit = PDFKit.new('http://google.com')
sadaf2605
  • 7,332
  • 8
  • 60
  • 103
  • Is there a possibility to generate the pdf from the current rendered page? Example. I have rendered a page and can see it in the browser. Full HTML-Code is generated. So I want to have a button to genereate a pdf from this HTML code. – Felix Oct 25 '15 at 16:52
  • @Felix just change `:action => "show.html.erb" ` which is your current page view file. – sadaf2605 Oct 26 '15 at 12:53