首页 > 解决方案 > Angular 5- PDF 文档,下载并在新窗口中显示

问题描述

我正在使用 Angular 作为前端,并且从 REST Full Web Service 获取数据。1)我需要在 Web 浏览器的新窗口中显示 pdf 文件,我从 Web 服务获取数据作为 base 64。

问题:我可以下载文件,但是当我尝试在新窗口中打开文件时,它会显示(错误:无法加载 pdf 内容)。这是我的代码:

服务:

this.http.get('https://localhost:44364/api/v1/source/GetImage/parameter1/animal.pdf', { responseType:'arraybuffer' })
    .subscribe(response => {
    var file = new Blob([response], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);

    this.content=this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
});

HTML:在 HTML 中,我使用 IFRAME 来显示 pdf 数据

iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="content"

任何人都可以帮助我。谢谢

标签: angularpdfiframe

解决方案


为了下载 pdf 文件,您可以尝试以下代码。您无法在桌面上打开 pdf 文件。

  this.httpClient.get('../assets/sample.pdf', { responseType: 'arraybuffer' 
    }).subscribe(response => {
      console.log(response);

      const file = new Blob([response], {type: 'application/pdf'});
      const fileURL = window.URL.createObjectURL(file);
      /*const link = document.createElement('a');
      link.href = fileURL;
      link.download = 'sample.pdf';
      link.click();*/
      if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveOrOpenBlob(file, fileURL.split(':')[1] + '.pdf');
      } else {
           window.open(fileURL);
      }
   });

}


推荐阅读