简体   繁体   English

无法在 Angular 应用程序中显示 PDF 文件

[英]Unable to display a PDF file in Angular app

I have a PDF file stored in a directory within the application ( assets/pdf/fileName.pdf ).我有一个 PDF 文件存储在应用程序内的目录中( assets/pdf/fileName.pdf )。 I need to display it on a new tab on a button click from a dialog.我需要在对话框中单击按钮时将其显示在新选项卡上。

Here is what I have, after looking at various answers:在查看了各种答案后,这是我所拥有的:

In *.component.ts:在 *.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');
      }
    );
  }

In *.service.ts:在 *.service.ts 中:

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

I already tried using responseType: 'arraybuffer' , but it didn't work out either.我已经尝试过使用responseType: 'arraybuffer' ,但也没有成功。

Here are the threads I have looked at:以下是我看过的主题:

I am not sure why are you using httpClient .我不确定你为什么使用httpClient The outcome that you want could be simply achieved by the following code您想要的结果可以通过以下代码简单地实现

In *.service.ts:在 *.service.ts 中:

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

In *.component.ts:在 *.component.ts 中:

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

You will either need to use the html embed tag (most likely also using a safe pipe), a PDF viewer (like Google PDF Viewer) or you can open the PDF in a new tab (this is the more common approach I see). You will either need to use the html embed tag (most likely also using a safe pipe), a PDF viewer (like Google PDF Viewer) or you can open the PDF in a new tab (this is the more common approach I see). It depends on your preference.这取决于您的喜好。

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

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