首页 > 解决方案 > 无法在 Angular 应用程序中显示 PDF 文件

问题描述

我有一个 PDF 文件存储在应用程序 ( assets/pdf/fileName.pdf) 的目录中。我需要在对话框中单击按钮时将其显示在新选项卡上。

在查看了各种答案后,这是我所拥有的:

在 *.component.ts 中:

  openPDF() {
    this.myService.fetchPDF().subscribe(
      res => {
        let file = new window.Blob([res], {type: 'application/pdf'});
        let fileURL = window.URL.createObjectURL(file);
        window.open(fileURL, '_blank');
      }
    );
  }

在 *.service.ts 中:

  fetchPDF(): any {
    const path = 'assets/pdf/fileName.pdf';
    return this.httpClient.get(PathResolver.resolveStatic(path),{responseType : 'blob'});
  }

我已经尝试过使用responseType : 'arraybuffer',但它也没有成功。

以下是我看过的主题:

标签: angularjsangular

解决方案


我不确定你为什么要使用httpClient. 您想要的结果可以通过以下代码简单地实现

在 *.service.ts 中:

fetchPDF(): any {
  const path = 'assets/pdf/fileName.pdf'
  return path;
}

在 *.component.ts 中:

openPDF() {
  window.open(this.myService.fetchPDF(), '_blank');
}

推荐阅读