Angular2 Displaying PDF

前端 未结 4 940
暗喜
暗喜 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 22:00

    First of all, you need to set options for your http request - set responseType to ResponseContentType.Blob, use blob() to read response as blob and set its type to application/pdf:

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

    Then, in order to get the file, you need to subscribe to it and you can create new ObjectURL and use window.open() to open PDF in new tab:

    this.myService.downloadPDF().subscribe(
            (res) => {
            var fileURL = URL.createObjectURL(res);
            window.open(fileURL);
            }
        );
    

提交回复
热议问题