16

I'm trying to understand the Prawn pdf gem.

I was able to make it generate a pdf. Every gem in the gemfile included:

gem 'mysql', '~> 2.8.1'
gem 'prawn', '~> 0.12.0'
gem 'pdf-reader', '~> 0.10.0'
gem 'Ascii85', '~> 1.0.1'

In the config/application.rb:

config.autoload_paths << "#{Rails.root}/app/reports"

Then in the controller:

 require 'prawn'

 def index
  pdf = Prawn::Document.new
  pdf.text "Hello World"
  pdf.render_file "x.pdf"
 end

Than I call the index function. A PDF named x.pdf is created in the root of my application. Amongst the gemfile, rakefile and config.ru.

Question:

  1. How can I force prawn to generate the file in the app/report (or any other selected) folder?
  2. How can I make the action to generate the file in the browser window and don't save it?
  3. How can I make it to save and show up in the browser window?
snowangel
  • 3,452
  • 3
  • 29
  • 72
Kael
  • 565
  • 2
  • 8
  • 18

3 Answers3

34

How can I force prawn to generate the file in the app/report (or any other selected) folder?

def index
  pdf = Prawn::Document.new
  pdf.text "Hello World"
  pdf.render_file File.join(Rails.root, "app/report", "x.pdf")
end

How can I make the action to generate the file in the browser window and don't save it?

def index
  pdf = Prawn::Document.new
  pdf.text "Hello World"
  send_data pdf.render, :filename => "x.pdf", :type => "application/pdf"
end

How can I make it to save and show up in the browser window?

def index
  pdf = Prawn::Document.new
  pdf.text "Hello World"
  filename = File.join(Rails.root, "app/report", "x.pdf")
  pdf.render_file filename
  send_file filename, :filename => "x.pdf", :type => "application/pdf"
end
Benoit Garret
  • 14,027
  • 4
  • 59
  • 64
  • 1
    Hi, for me its not going to save in that folder. but it goes there to find that is that pdf is there or not? any solution to store pdf in public folder? – SSR Sep 09 '13 at 12:59
  • 4
    in the send_data you should add the option :disposition => 'inline' – sissy Feb 21 '14 at 17:29
20

Answering Question 3: "How can I make it to save and show up in the browser window?"

def index
  pdf = Prawn::Document.new
  pdf.text 'Hello World'
  send_data pdf.render, filename: 'x.pdf', type: 'application/pdf', disposition: 'inline'
end

disposition: 'inline' will force the browser ( if it can ) to display your PDF inside the current browser window

Justin Tanner
  • 14,062
  • 17
  • 82
  • 103
0

Try this:

 def index
  pdf = Prawn::Document.new
  pdf.text "Hello World"
  send_data pdf.render, :filename => "x.pdf", :type => "application/pdf"
 end

That said, for anything but a trivial PDF you will probably want to generate it outside the controller somewhere.

James Healy
  • 14,557
  • 4
  • 33
  • 43