如何在ROR(Ruby)中显示PDF?

Doo*_*ght 34 ruby pdf ruby-on-rails

我在互联网上环顾四周,但似乎无法找到如何在rails中显示PDF(我只能找到有关如何创建PDF的信息).

有谁知道我需要显示哪个代码/ gem?

Ben*_*ret 52

在你的控制器中:

def pdf
  pdf_filename = File.join(Rails.root, "tmp/my_document.pdf")
  send_file(pdf_filename, :filename => "your_document.pdf", :type => "application/pdf")
end
Run Code Online (Sandbox Code Playgroud)

config/environment/production.rb:

config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
Run Code Online (Sandbox Code Playgroud)

要么

config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
Run Code Online (Sandbox Code Playgroud)

配置修改是必需的,因为它使Web服务器能够直接从磁盘发送文件,从而提供了良好的性能提升.

更新

如果要显示它而不是下载它,请使用以下:disposition选项send_file:

send_file(pdf_filename, :filename => "your_document.pdf", :disposition => 'inline', :type => "application/pdf")
Run Code Online (Sandbox Code Playgroud)

如果你想以内联方式显示它,那么这个问题将会更加完整.

  • 更新了我的回答. (5认同)
  • 这样做对我来说:`send_file(...,disposition:'inline')` (2认同)

and*_*ham 6

基本上你只需要在视图中的html中编写它.所以这个简单的解决方案对我有用:

在'show.hmtl.erb'中

<iframe src=<%= @certificate.certificate_pdf %> width="600" height="780" style="border: none;"> </iframe>
Run Code Online (Sandbox Code Playgroud)

只需将文件位置放在嵌入式ruby中作为iframe标记的来源,经过数小时和数小时的搜索就能为我工作.'certificate'是我的模型,'certificate_pdf'是我的附件文件.