Angular 4 : Convert Response from API to PDF

enter image description here

Hello everyone, I got a problem when I try to convert response from API, i got an error

The request body isn't either a blob or an array buffer

Here is my code

app.service.ts

downloadPDF(id_booking): any {
  let headers = new Headers();
  this.createAuthorizationHeader(headers);
  return this.http.post('https://localhost:1210/v1/user/booking/eticket/'+id_booking, {responseType: ResponseContentType.Blob}, {headers: headers}).map(
  (res) => {
    console.log(res)
    return new Blob([res.blob()], { type: 'application/pdf' })
  })
}

pdf.component.ts

this.appService.downloadPDF(booking._id).subscribe(
    (res) => {
    saveAs(res, "myPDF.pdf"); 
    var fileURL = URL.createObjectURL(res);
    window.open(fileURL);
    }

2 answers

  • answered 2018-11-08 08:02 user184994

    Your backend is currently sending a string.

    Assuming you're using express, instead of

    res.send(arr)
    

    You should use

    res.send(buffer);
    

    This will ensure the binary data is sent

  • answered 2018-11-08 08:31 Exodius35

    @user184994

    enter image description here

    I still got the same error..

    Here is the backend code

    pdf.create(document, config)
            .then(file => {
                    var buffer = Buffer.from(file);
                    res.end(buffer,'binary')
            })
            .catch(error => {
                    console.error(error);
    })