我在Rails(3.1.1)的最新版本的Prawn库(v1.0.1rc)中创建了一个pdf文件,当我运行我的代码时,它会将PDF生成到应用程序的根目录中.
我不想要这个我希望它将输出渲染到用户的浏览器窗口中,而不将其保存在本地到服务器.
请告诉我如何实现这一点.这是我的文件:
意见/富/ show.pdf.erb:
<%= require 'prawn' pdf = Prawn::Document.new(:page_size => 'LETTER',:page_layout => :landscape,:margin => 50,:top_margin => 20,:bottom_margin => 50) ..... render_file("foo.pdf") %>
控制器/ foo_controller:
class AuditsController < ApplicationController before_filter :authenticate_user! layout 'application' can_edit_on_the_spot respond_to :html,:xml,:js,:pdf def index @audits = Audit.all respond_with @audits end def show @audit = Audit.find(params[:id]) respond_with @audit do |format| format.pdf { render :layour => false } end end
解决方法
的Gemfile
gem 'prawn'
/config/initializers/mime_types.rb
Mime::Type.register "application/pdf",:pdf
AuditsController
def show @audit = Audit.find(params[:id]) respond_to do |format| format.html format.pdf do pdf = Prawn::Document.new pdf.text "This is an audit." # Use whatever prawn methods you need on the pdf object to generate the PDF file right here. send_data pdf.render,type: "application/pdf",disposition: "inline" # send_data renders the pdf on the client side rather than saving it on the server filesystem. # Inline disposition renders it in the browser rather than making it a file download. end end end
我曾经在Rails 3.1之前使用prawnto gem,但是如果没有一点黑客,它就不行.这是通过直接访问Prawn来实现和显示3.1中的PDF对象的更干净的方式.
我从Ryan Bates的Railscasts之一直接得到了这种技术.您可以查看具体情节here.他详细介绍了将Prawn子类化并将PDF生成代码移出控制器.还显示了很多有用的Prawn方法让你开始.强烈推荐.