如何在通过rails控制器检索的浏览器中呈现PDF

我有一个使用Recurly的rails应用程序。 我正在尝试下载PDF并在浏览器中呈现它。 我目前有一个链接:

link_to 'Download', get_invoice_path(:number => invoice.invoice_number) 

关联的控制器具有get_invoice方法,如下所示:

 def get_invoice begin @pdf = Recurly::Invoice.find(params[:number], :format => 'pdf') rescue Recurly::Resource::NotFound => e flash[:error] = 'Invoice not found.' end end 

当我点击链接时,我得到了在我的控制台中以二进制forms呈现的PDF。 如何在浏览器中渲染PDF?

假设PDF保存在内存中,请使用send_data在浏览器中发回数据流。

 def get_invoice @pdf = Recurly::Invoice.find(params[:number], :format => 'pdf') send_data @pdf, filename: "#{params[:number]}.pdf", type: :pdf end 

如果文件存储在某个地方(但这似乎不是你的情况),请使用send_file

您不将PDF呈现给浏览器,而是将其作为文件发送。 像这样:

 # GET /something/:id[.type] def show # .. set @pdf variable respond_to do |format| format.html { # html page } format.pdf do send_file(@pdf, filename: 'my-awesome-pdf.pdf', type: 'application/pdf') end end end 

如果您不支持多种格式,则不需要HTML响应。

如果要在浏览器中显示PDF而不是开始下载,请在send_file调用中添加disposition: :inline send_file