代码之家  ›  专栏  ›  技术社区  ›  Nancy

下载到PDF不工作

  •  1
  • Nancy  · 技术社区  · 7 年前

    我有以下代码从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 回复  |  直到 7 年前
        1
  •  1
  •   tatsu    7 年前

    有很多事情需要改变,下面是我的工作:

    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;
    }
    

    我个人在一个post请求中使用了它,但get显然是更常见和更明显的场景。

    我最终在angular上的一期github长刊中偶然发现了这一点。

    双重诀窍是将文本转换为文本,并使http调用中的所有选项看起来尽可能脏。

    我还加入了我的语法,在那里我首先声明了一个var并返回了它(如果突然需要控制台再次记录它,那么这不一定是浪费一行代码),并且还添加了一个catch,您可以在所有api的全局catch函数中处理它。

    别忘了喜欢、喜爱和 订阅 到您的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');
      }
    
        2
  •  0
  •   Kelvin Lai    7 年前

    您需要创建一个订阅 downloadPdf 函数并打开指向 blob :

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