简体   繁体   English

在新标签角 4 中打开 PDF 文件?

[英]Opening PDF file in new tab angular 4?

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.我尝试使用window.open()打开 PDF 文件,但窗口会自动打开和关闭,并且文件会像任何其他文件一样被下载。 How to make the pdf file open in new tab?如何使pdf文件在新标签页中打开? There are no ad blockers installed.没有安装广告拦截器。

From @barbsan idea, I changed the http headers and received a blob and used that to display the blob as pdf using window.open().根据@barbsan 的想法,我更改了http 标头并收到了一个blob,并使用window.open() 将blob 显示为pdf。 It worked.有效。

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');
});

One liner solution to open a pdf file in new tab.在新选项卡中打开 pdf 文件的一种线性解决方案。 You just need to have file url and use this function on button click.您只需要拥有文件 url 并在按钮单击时使用此功能。

window.open(url, '_blank');

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>

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 是一个包含文件路径的变量。

How to make it work in Angular 10, changes just a little bit, this in the service file from @K Harish answer如何使其在 Angular 10 中工作,只需稍作改动,这在 @K Harish 的服务文件中回答

import { map } from 'rxjs/operators';


    return this.http.get(url, options).pipe(map(
    (res) => {
        return new Blob([res], { type: 'application/pdf' });
    }));

For the Angular 13 version对于 Angular 13 版本

downloadPDF(url: string): Observable<Blob> {
   const options = { responseType: 'blob' as 'json' };
   return this.httpClient
  .get<Blob>(url, options)
  .pipe(map(res => new Blob([res], { type: 'application/pdf' })));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM