在 Rails 中强制内联渲染 PDF 文档
我正在编写一个从一组 XML 文件生成 PDF 文件的服务。正在正确生成 PDF。但是,每次我单击“查看 PDF”链接时,浏览器都会要求用户下载 PDF 文件。
我需要 PDF 内联显示,就像任何常规 HTML 页面一样。我虽然我写的代码是正确的,但一定缺少一些东西 - 浏览器不断要求用户下载。
这是当前的代码:
class PdfController < Controller
def generate
# stuff
send_data pdf_bytes, :disposition => 'inline', :type => 'application/pdf'
end
end
有什么想法吗?
I'm writing a service that generates PDF files from a set of XML files. The PDF is being correctly generated. However, everytime I click on the "view PDF" link, the browser asks the user to download the PDF file.
I need the PDF to display inline, just like any regular HTML page. I though I wrote the code right, but something must be missing - the browser keeps asking the user to download.
Here's the current code:
class PdfController < Controller
def generate
# stuff
send_data pdf_bytes, :disposition => 'inline', :type => 'application/pdf'
end
end
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试完全删除
Content-Disposition
标头。根据我的经验,Content-Disposition:attachment
工作得很好,但许多浏览器对于任何其他值的行为都不一致。如果您想内联显示,最好删除标题并希望得到最好的结果。 IE 似乎对这个标头的问题最多。 (惊喜,惊喜。)只需确保您仍在设置Content-Type: application/pdf
即可。另一种选择是使用
iframe
并将iframe
的src
设置为您的 PDF 文件。几乎所有支持内联 PDF 查看的浏览器都能正确处理此问题。缺点是您最终可能会显示一个空白的iframe
,而不受支持的浏览器本来可以优雅地回退到简单地下载 PDF。Try removing the
Content-Disposition
header altogether. It's been my experience thatContent-Disposition: attachment
works pretty well, but many browsers have inconsistent behavior for any other value. If you want to display inline, it might just be better to remove the header and hope for the best. IE seems to have the most problems with this header. (Surprise, surprise.) Just make sure you're still settingContent-Type: application/pdf
.The other option would be to use an
iframe
and set thesrc
of theiframe
to your PDF file. Almost all browsers that support inline PDF viewing will handle this correctly. The downside is that you might end up displaying a blankiframe
whereas non-supported browsers would have otherwise done a graceful fallback to simply downloading the PDF.