2

I'm pretty new to Rails development and I can't understand how to embed a PDF file in the browser. I already looked for others questions on the same subject like this and I'm dumbfounded. Already changed all the answer said but it just doesn't work.

This is my function

# create pdf function
  def pdf
    menu_pdf = File.join(Rails.root, 'app/assets/files/menulq2.pdf')
    send_file(menu_pdf, filename: 'menulq2.pdf.pdf', disposition: 'inline', type: 'application/pdf')
  end

And now I don't know what to do next.

IanH
  • 21
  • 2

1 Answers1

0

The SO Answer you link to is about downloading/sending PDF files to/from your server. You needed to scroll down farther to read about displaying PDFs within your HTML views.

There's no reason to have a SomeModel#pdf method in your Model unless each record links to a specific PDF (e.g. if the model were Restaurant and you had a PDF menu for each restaurant.


You can just use an HTML embed tag:

<embed src="http://example.com/the.pdf" width="500" height="375" type="application/pdf">

As long as the path for 'app/assets/files' is in the asset pipeline , you can use asset_path helper:

<embed src="<%= asset_path('menulq2.pdf') %>" width="500" height="375" 
 type="application/pdf">

The benefit here is if your assets are getting precompiled, the filename might be changed from menulq2.pdf to something like menulq2-60aa4fdc5cea14baf5400fba1abf4f2a46a5166bad4772b1effe341570f07de9.pdf, in which case, you as the developer, don't actually know what the PDF's filename actually is.

So the asset_path helper allows you to specify the simple filename and not worry about what asset compliation might have done to the name.


If that's too fiddly, or you know this asset isn't getting precompiled, you can hard-code it into the HTML:

<embed src="/assets/files/menulq2.pdf" width="500" height="375" 
 type="application/pdf">

To hard-code the URL you need to make sure you are serving static files by setting this to true in your environment files (/config/environments/*.rb):

For Rails 4: config.serve_static_files = true

For Rails 5+: config.public_file_server.enabled = true

Chiperific
  • 4,428
  • 3
  • 21
  • 41