【问题标题】:how to download PDF in angular 7?如何以 Angular 7 下载 PDF?
【发布时间】:2019-04-26 20:37:06
【问题描述】:

请求:

组件.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 [作为调用] (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.parse ()↵ 在 XMLHttpRequest.onLoad 的位置 0↵ 的 JSON 中的意外标记 % (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)↵ 在 调用任务 (http://localhost:4200/polyfills.js:4102:14)↵ 在 XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4139:21)" 原型:错误 文本:“%PDF-1.5↵%����↵3 0 obj↵

【问题讨论】:

  • 可能需要在请求选项中添加{responseType: 'blob'}。看看这是否有帮助:stackoverflow.com/questions/53758280/…
  • 我不确定,但我猜你正在获取的数据是在 json 中解析的(默认情况下)。我认为它在新版本 express 中的正常行为......你能看看吗响应对象?
  • 好的。我正在尝试响应类型
  • 我相信你不会从subscribe() 的回复中得到太多,因为你发送的是postrequest(除非你在请求选项中使用{observe: 'response'})。控制台中打印的响应是什么?
  • responseType: blob 不工作

标签: javascript java angular angular7


【解决方案1】:

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

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' , "");

只需在 url 后面附加你的变量。

【讨论】:

    【解决方案2】:

    你需要使用地图功能

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

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多