如何在angular 7中下载PDF?

时间:2019-04-26 05:31:52

标签: javascript java angular angular7

请求:

component.ts

    getRevenueReport() {

        const revenueReport = {
              dateFrom: '1/04/2019',
              dateTo: '23/04/2019',
       };

        this.apiService.getRevenueReport(revenueReport).subscribe( response => {
              console.log('response: ', response);
              const mediaType = 'application/pdf';

              const blob = new Blob(response, { type: mediaType });

              saveAs(blob, 'revenue.pdf');

            }, error => {
              console.log('error: ', error);
            });
    }

service.ts:

    getRevenueReport(revenueReport): any {
        const options = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            Accept: '*/*',
            Authorization: 'apiKey 8989jjjhjhgghghg765756',
          })
        };
        return this.http.post(this.BASE_API_URL + '/api/report', revenueReport, options);
      }

我正在尝试下载PDF。我收到错误

  

错误:SyntaxError:JSON中位于位置0的意外令牌%   XMLHttpRequest.onLoad上的JSON.parse()   (http://localhost:4200/vendor.js:13601:51)在   ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask   (http://localhost:4200/polyfills.js:2781:31)在Object.onInvokeTask   (http://localhost:4200/vendor.js:59081:33)在   ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask   (http://localhost:4200/polyfills.js:2780:60)在   Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask   (http://localhost:4200/polyfills.js:2553:47)在   ZoneTask.push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask   [in invokeTask的[as invoke](http://localhost:4200/polyfills.js:2856:34)   (http://localhost:4200/polyfills.js:4102:14)在   XMLHttpRequest.globalZoneAwareCallback   (http://localhost:4200/polyfills.js:4139:21)           消息:“位置0的JSON中的意外令牌%”           堆栈:“ SyntaxError:JSON中意外的令牌%在XMLHttpRequest.onLoad的JSON.parse()↵的位置0↵   (http://localhost:4200/vendor.js:13601:51)↵在   ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask   (http://localhost:4200/polyfills.js:2781:31)↵在   Object.onInvokeTask(http://localhost:4200/vendor.js:59081:33)↵在   ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask   (http://localhost:4200/polyfills.js:2780:60)↵在   Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask   (http://localhost:4200/polyfills.js:2553:47)↵在   ZoneTask.push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask   [在调用时](http://localhost:4200/polyfills.js:2856:34)在   invokeTask(http://localhost:4200/polyfills.js:4102:14)↵在   XMLHttpRequest.globalZoneAwareCallback   (http://localhost:4200/polyfills.js:4139:21)”           原始:错误           文字:“%PDF-1.5↵%����↵30obj↵<

2 个答案:

答案 0 :(得分:1)

重要-在请求标头中,将响应类型作为'json'添加到'arraybuffer'中,否则将不起作用

fetchPDF(url: string,data): Observable<any> {
this.getCredentials();
const authHeaders = this.createBasicAuthorizationHeader(this.credentials);
 return this.http.post(this.getApiUrl(url),data,{headers: authHeaders,'responseType'  : 'arraybuffer' as 'json'})
 }



exportPDF(){
this.httpRestClient.fetchPDF("download_salary_report", revenueReport ).subscribe(
  response => {
    var blob = new Blob([response], {type: 'application/pdf'});
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE');
    var trident = ua.indexOf('Trident/');
    var edge = ua.indexOf('Edge/');

  if(msie > 0 || trident > 0 || edge > 0){
    window.navigator.msSaveOrOpenBlob(blob,'revenue.pdf');
}
else if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = "revenue.pdf";
    document.body.appendChild(link);
    link.click();

    window.setTimeout(function() {
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }, 0);

}
  else{ 

  var link=document.createElement('a');
  link.href=window.URL.createObjectURL(blob);
  link.download="revenue.pdf";
  link.click();


  }

    },
  error=>{
  // show your error message here

  });


 }

或者您也可以像这样使用get请求。

 window.open(appConfig.DOMAIN_NAME+"export_report_item_consumption/"+(itemName+ "," +this.datepipe.transform(this.payloadBean.fromDate, 'yyyy-MM-dd')
   + "," +this.datepipe.transform(this.payloadBean.toDate, 'yyyy-MM-dd')+","+this.currentuser.userID).toString(),'_blank' , "");

只需在网址后附加变量即可。

答案 1 :(得分:0)

您需要使用地图功能

getRevenueReport(revenueReport): any {
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Accept: '*/*',
        Authorization: 'apiKey hjhjhjhu787878hjhjhjhzBa',
      })
    };
    this.http.post(this.BASE_API_URL + '/api/report', revenueReport, options).pipe(
      map((res) => {
         return new Blob([res.body], { type: res.headers.get('Content-Type') });
      })
    );
  }