How do I display a PDF in ROR (Ruby)?
I have looked around on the internet, but do not seem able to find how to display a PDF in rails (I can only find info on how to create one).
Does anyone know what code/gem I need to display one?
In your controller:
def pdf
pdf_filename = File.join(Rails.root, "tmp/my_document.pdf")
send_file(pdf_filename, :filename => "your_document.pdf", :type => "application/pdf")
end
In config/environment/production.rb
:
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
or
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
The config modification is required because it enables the web server to send the file directly from the disk, which gives a nice performance boost.
Update
If you want to display it instead of downloading it, use the :disposition
option of send_file
:
send_file(pdf_filename, :filename => "your_document.pdf", :disposition => 'inline', :type => "application/pdf")
If you want to display it inline, this question will be much more complete that I could ever be.
Basically you just need to write it in the html in your view. So this simple solution worked for me:
In the 'show.hmtl.erb'
<iframe src=<%= @certificate.certificate_pdf %> width="600" height="780" style="border: none;"> </iframe>
just putting the file location in embedded ruby as the source of the iframe tag worked for me after hours and hours of searching. 'certificate' is my model, and 'certificate_pdf' is my attachment file.
Depending where the PDF comes from, the following may help you. I have an application where I store a lot of things, and some of them have (additional) PDFs connected to the items. I store the items in the directory /public/res/<item_id>/
. res
means result, and item_id
is the numeric id of that item in Rails.
In the view, I provide a link to the PDFs by the following (pseudo-)code as a helper method, that may be used in the view:
def file_link(key, name = nil)
res= Ressource.find(:first, :conditions => ["key = ?", key])
list = Dir["public/res/#{res.id}/*"]
file= list.empty? ? "" : list[0]
return file if file.empty?
fn = name ? name : File.basename(file)
link_to fn, "/res/#{res.id}/#{File.basename(file)}", :popup => true
end
The relevant part here is the link_to name, "/res/#{res.id}/#{File.basename(file)}"
thing.
上一篇: 如何在网站中嵌入PDF文件?
下一篇: 如何在ROR(Ruby)中显示PDF?