Angular2 Displaying PDF

前端 未结 4 948
暗喜
暗喜 2020-12-07 21:19

I have an angular2 project with an ASP.Net Web API. I have code to retrieve a file path from my database which goes to a document on my server. I then want to display this d

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 21:59

    Angular v.5.2.1 answer:

    In *.services.ts

    downloadPDF(): any {
        return this._httpClient.get(url, { responseType: 'blob'})
                .map(res => {
                return new Blob([res], { type: 'application/pdf', });
            });
      }
    

    And then in *.component.ts

    downloadPDF() {
        let tab = window.open();
        this._getPdfService
          .downloadPDF()
          .subscribe(data => {
            const fileUrl = URL.createObjectURL(data);
            tab.location.href = fileUrl;
          });
      }
    

    Its important to initiate and open a new tab before calling the service. Then set this tabs url to the fileurl.

提交回复
热议问题