Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render PDF in Browser (instead of download default)

I store PDF receipts in S3. I use WickedPDF for generating the PDF files. Via the admin area of our app, there is a "Download" link, that is simply a direct link to the S3 path:

link_to "Download", order.receipt.url unless order.receipt.blank?

Any idea on how I can have it default to opening in a browser window instead of direct download?

like image 256
Ryan Rebo Avatar asked Oct 24 '25 16:10

Ryan Rebo


1 Answers

The trick is to change the headers, if you link to a static file your webserver (S3) will add a header Content-Disposition: attachment; filename="name.pdf" without this header the browser will try to render this inline (same window).

To solve this issue you could have an action on your controller that downlaods the file itself and steams it to the user

require "open-uri"

class OrderController
  def  receipt
    @order=Order.find(....)

    render text: open(@order.receipt.url).read, content_type=>'application/pdf'
  end
end

Obviously add a route to it identifying the order and link to this new action, this will render the pdf downloaded by rails without the 'attachment' header.

like image 67
ahmeij Avatar answered Oct 26 '25 06:10

ahmeij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!