Rails 4 - 如何创建指向 PDF 文件(name.PDF)的链接? [英] Rails 4 - how to make a link to a PDF file (name.PDF)?

查看:59
本文介绍了Rails 4 - 如何创建指向 PDF 文件(name.PDF)的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成 PDF 文件,我的链接如下所示:

I am generating PDF files and my link look like this:

<%= link_to 'Invoice', display_invoice_path(invoice.id), :format => :pdf %>

当我点击它时,它会将我带到 /display_invoice/123456789(这是一个 HTML 版本).

When I click on this, it takes me to /display_invoice/123456789 (it's an HTML version).

在控制器中的动作如下:

In the controller action is following:

def display_invoice
    if params[:invoice_number]
      @invoice = ...

      respond_to do |format|
        format.html
        format.pdf do
          #render pdf: '123',                  # file name
          render pdf: params[:invoice_number],
                 layout: 'layouts/application.pdf.erb'#,  # layout used
                 #show_as_html: params[:debug].present?    # allow debuging
        end
      end
    end
  end

在路线中:

  get '/display_invoice/:invoice_number', to: 'invoices#display_invoice', :as => 'display_invoice'

点击链接后,我希望在 URL /display_invoice/INVOICE_NUMBER.pdf 中有一个 - 目前只有 /display_invoice/INVOICE_NUMBER.

After clicking the link, I'd like to have in the URL /display_invoice/INVOICE_NUMBER.pdf - currently, there's just /display_invoice/INVOICE_NUMBER.

如何用.pdf"后缀打开它?

How to open it with the ".pdf" suffix?

谢谢.

推荐答案

您需要添加 pdf mime 类型.

You need to add the pdf mime type.

将以下行添加到文件 config/initializers/mime_types.rb:

Add the following line to the file config/initializers/mime_types.rb:

Mime::Type.register "application/pdf", :pdf

参见 http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads 详情.

格式需要成为路径助手的一部分:

The format needs to be part of the path helper:

display_invoice_path(invoice.id, :format => :pdf)

这篇关于Rails 4 - 如何创建指向 PDF 文件(name.PDF)的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆