Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - how to make a link to a PDF file (name.PDF)?

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

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

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

and in the routes:

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

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.

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

Thank you.

like image 541
user984621 Avatar asked Aug 26 '14 09:08

user984621


People also ask

How to make PDF from link?

In the open web page, right-click the linked text and choose one of the following: To add the linked web page to an existing PDF, choose Append Link Target To Existing PDF. Then locate and select the existing PDF, and click Save. To convert the linked web page to a new PDF, choose Convert Link Target To Adobe PDF.

How do you download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.


2 Answers

You need to add the pdf mime type.

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

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

See http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads for details.

EDIT:

The format needs to be part of the path helper:

display_invoice_path(invoice.id, :format => :pdf)
like image 106
koffeinfrei Avatar answered Sep 27 '22 18:09

koffeinfrei


use this code instead of your code

<%= link_to 'Invoice', display_invoice_path(invoice.id, :format => :pdf) %>
like image 33
navinspm Avatar answered Sep 27 '22 20:09

navinspm