在浏览器中呈现PDF文件(而不是默认下载)

4

我将PDF收据存储在S3中。我使用WickedPDF生成PDF文件。通过我们应用程序的管理区域,有一个“下载”链接,它只是指向S3路径的直接链接:

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

有没有办法让它默认在浏览器窗口中打开,而不是直接下载?
4个回答

1
关键是要更改标题,如果链接到静态文件,则您的Web服务器(S3)将添加一个标题Content-Disposition: attachment; filename="name.pdf",没有此标题,浏览器将尝试内联呈现该文件(同一窗口)。
为了解决这个问题,您可以在控制器上设置一个操作,将文件本身下载并流式传输给用户。
require "open-uri"

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

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

很明显,需要添加一个路由来识别订单并链接到这个新操作,这将呈现由Rails下载的PDF,而不带有“attachment”标头。

0
如果要在页面的某个部分显示PDF,您可以在页面上使用以下代码。
<object data="<%= upload.file.url %>" width="100%" height="100%" style="min-height: 100%; height:100%; width:100%" type="<%= upload.mime_type %>">
  <p>No PDF render functionality on your device...</p>
</object>

如果您只想展示 PDF 文件并将其显示为完整页面文件,请在您的控制器中使用以下代码(即时创建 PDF 文件)。
pdf = @sales_invoice.pdf
send_data pdf.render, filename: "sales_invoice.pdf",
                      type: "application/pdf",
                      disposition: "inline"

0

渲染 PDF:

render pdf: "Invoice",
       orientation: 'Portrait',
       template: "Invoice/download",
       page_size:  'Letter'

-1

1
请不要提供仅链接的答案。链接在互联网上很快就会失效,然后这个答案就毫无价值了。请在答案中包含您想表达的相关部分。 - Prasad Khode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接