0

I'm trying to generate a PDF file from an endpoint, the showPDF function has an ID parameter of the Product and generate a PDF as an output.

I've tried to declare a Promise to get the bytes stream from that endpoint:

    showPdf(rowData: Product) {

    console.log("ID = >" + rowData.id);

    let promise = new Promise((resolve, reject) => {
      let apiURL = this.apiUrl + "/api/products/get/pdf/"+rowData.id;
      this.http.get(apiURL)
      .toPromise()
      .then(
        res => { // Success
       
        this.results = String(res);
        console.log("Bytes=> " + res);
       
        resolve();
        },
        msg => { // Error
        reject(msg);
        }
      );
  });  
    const bytes = this.results; 
    const linkSource = 'data:application/pdf;base64,'+ bytes;
    const downloadLink = document.createElement("a");
    const fileName = "Report.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    console.log("downloadLink = >" + downloadLink);
    downloadLink.click();
}

The issue is that the downloadlink is executed before getting the result from the Promise.

For instance, when calling showPDF(942) I get an undefined value of the download link

enter image description here

When calling showPDF for the same ID or another ID value, it generates the PDF but from the previous bytes stream value got from the Promise.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Angelika
  • 23
  • 1
  • 11

1 Answers1

0

You can try like this

showPdf(rowData: Product) {
    console.log("ID = >" + rowData.id);
    let promise = new Promise((resolve, reject) => {
      let apiURL = this.apiUrl + "/api/products/get/pdf/"+rowData.id;
      this.http.get(apiURL)
      .toPromise()
      .then(
        res => { // Success

        this.results = String(res);
        console.log("Bytes=> " + res);
// here after getting the result we are calling the another function to download the PDF
        this.downLoadPdf();
        resolve();
        },
        msg => { // Error
        reject(msg);
    }
   );
  });  
}

downLoadPdf() {
    const bytes = this.results; 
    const linkSource = 'data:application/pdf;base64,'+ bytes;
    const downloadLink = document.createElement("a");
    const fileName = "Report.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    console.log("downloadLink = >" + downloadLink);
    downloadLink.click();
}
Yash Rami
  • 2,276
  • 1
  • 10
  • 16
  • Thank you for your response, when I'm calling the function downloadPDF, it works : the PDF file is generated with the right download link value, however the generation process is very slow, while the first code generate the PDF instantly – Angelika Mar 12 '20 at 13:14
  • @Angelika Yes because it is waiting for the API call to complete – Yash Rami Mar 12 '20 at 13:36