下载到PDF不起作用

时间:2018-04-24 10:21:13

标签: angular pdf download

我有以下代码从url下载JSON对象。但下载没有发生。

     openDownloadWindow() {
    this.downloadPdf().subscribe(pdfBlob => {
        const url = window.URL.createObjectURL(pdfBlob);
        window.open(url);
    });
}
public downloadPdf() {
  const url =  'http://161.202.31.51:8185/sgdocsrv/ar/getARList';
  const headers = new Headers();
  headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
  return this.http.get(url, {  headers: headers, responseType: ResponseContentType.Blob }).map(
      (res) => {
          return new Blob([res.blob()], { type: 'application/pdf' });
      });
}

2 个答案:

答案 0 :(得分:1)

我需要改变一些事情,所以这就是我的工作:

public getMeMyPDF(): any {
    const url =  'http://161.202.31.51:8185/sgdocsrv/ar/getARList';
    this.PDF = this.http.get(url, {
      observe: 'response',
      headers: new HttpHeaders({'Content-Type', 'application/pdf', 'Authorization',
      'JWT ' + localStorage.getItem('id_token')}),
      responseType: 'text' as 'text' // <-- this part is rediculous but necessary
    }).catch(this.handleError);
    return this.PDF;
}

我个人在一个帖子请求中有它,但显然是更常见和明显的情况。

我终于在角色的长期github问题上偶然发现了这个问题。

双重技巧是从文本到文本进行转换,并使您在http调用中的整个选项看起来像脏的一样。

我还提到了我的语法,我首先声明了var并返回了它(如果突然你需要再次登录它就不一定浪费一行),还添加了一个你可以在全局捕获中处理的catch适用于所有API。

不要忘记喜欢,喜欢和订阅到你的api,无论你在哪里打电话。 (即使你没有在订阅中做任何事情(在你的情况下你会)(

这是我在调用我的apiservice.getMeMyPDF的组件中所做的事情:

getMeAPDF(){
    this.apiService.getMeMyPDF().subscribe(res => {
      if(res !== null && res !== undefined){
        this.saveToFileSystem(res.body);
      }
    }, (error) => console.log(error), () => {});
  }

  private saveToFileSystem(response) {
    const blob = new Blob([response], { type: 'text/pdf' });
    const d = new Date();
    saveAs(blob, 'WOWPDF_' + this._datepipe.transform(d, 'yyyyMMdd_HHmmss') + '.pdf');
  }

答案 1 :(得分:0)

您需要创建一个订阅downloadPdf功能的新功能,并打开指向blob的链接:

openDownloadWindow() {
    this.downloadPdf().subscribe(pdfBlob => {
        const url = window.URL.createObjectURL(pdfBlob);
        window.open(url);
    });
}
相关问题