Javascript 以新标签 angular 4 打开 PDF 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51204276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Opening PDF file in new tab angular 4?
提问by k harish
I tried opening a PDF file using the window.open(), but the window opens and closes automatically and the file is downloaded like any other file. How to make the pdf file open in new tab? There are no ad blockers installed.
我尝试使用 来打开 PDF 文件window.open(),但窗口会自动打开和关闭,并且该文件会像任何其他文件一样下载。如何在新标签页中打开pdf文件?没有安装广告拦截器。
回答by k harish
From @barbsan idea, I changed the http headers and received a blob and used that to display the blob as pdf using window.open(). It worked.
根据@barbsan 的想法,我更改了 http 标头并收到了一个 blob,并使用它使用 window.open() 将 blob 显示为 pdf。有效。
Here is my sample code.
这是我的示例代码。
In service file
在服务文件中
downloadPDF(url): any {
const options = { responseType: ResponseContentType.Blob };
return this.http.get(url, options).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' });
});
}
In component file
在组件文件中
this.dataService.downloadPDF(url).subscribe(res => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL, '_blank');
});
回答by Waleed Shahzaib
One liner solution to open a pdf file in new tab. You just need to have file url and use this function on button click.
在新选项卡中打开 pdf 文件的一种班轮解决方案。您只需要拥有文件 url 并在单击按钮时使用此功能。
window.open(url, '_blank');
window.open(url, '_blank');
回答by Hoiama Rodrigues
you need user the "target="_blank" in the tag ;
您需要用户在标签中使用“ target=”_blank”;
exemple: <a target="_blank" href="https://www.google.com/"> </a>
例子: <a target="_blank" href="https://www.google.com/"> </a>
回答by lea
you can display pdf fle in new tab by the line:
您可以按以下行在新选项卡中显示 pdf 文件:
window.open(fileUrl, '_blank');
The fileUrl is a variable that contains the file path.
fileUrl 是一个包含文件路径的变量。

