如何在Sulu CMS中在浏览器内显示PDF文档
解决方案
有两种简便方法可以实现在浏览器内显示PDF,而非直接触发下载:
方法1:将PDF嵌入页面中
修改你的document.html.twig模板,用<iframe>或<embed>标签替代原有的链接,让PDF直接在页面内渲染:
使用iframe(兼容性更好)
<ul> {% for document in content.documents %} <li> <iframe src="{{ document.url }}" width="100%" height="600px" title="{{ document.title }}"> <!-- 浏览器不支持iframe时的降级方案 --> <a href="{{ document.url }}">{{ document.title }}</a> </iframe> </li> {% endfor %} </ul>
使用embed标签
<ul> {% for document in content.documents %} <li> <embed src="{{ document.url }}" type="application/pdf" width="100%" height="600px"> <!-- 降级链接 --> <a href="{{ document.url }}">{{ document.title }}</a> </embed> </li> {% endfor %} </ul>
这种方式依赖现代浏览器自带的PDF渲染引擎,无需额外插件。
方法2:在新标签页预览PDF
如果希望保留链接形式,但点击后在新标签页显示PDF而非下载,可给链接添加target="_blank"属性:
<ul> {% for document in content.documents %} <li> <a href="{{ document.url }}" target="_blank" rel="noopener noreferrer"> {{ document.title }} </a> </li> {% endfor %} </ul>
注意:这种方式生效的前提是服务器返回的Content-Disposition响应头为inline(而非attachment)。如果服务器配置强制下载,需要调整服务器的文件响应头设置(比如Apache的Header set Content-Disposition "inline",或Nginx的add_header Content-Disposition inline;)。
内容的提问来源于stack exchange,提问作者Waldo
相关产品推荐
相关产品推荐

