Save a PDF generated by SpringBoot in Angular

Published

I am trying to save a PDF using Angular and Spring Boot.

When I make an API call, my Java code is fetching the data from the database and transforming it to a byte-stream. This stream is sent as response.

if(format.equals(Constant.PDF_FORMAT)) {
    ByteArrayInputStream stream = reportPDF.generateReportDocument(dtos);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "inline; filename=report.pdf");
    return ResponseEntity.ok()
                         .headers(headers)
                         .contentType(MediaType.APPLICATION_PDF)
                         .body(new InputStreamResource(stream));
}

I have to use this response and save the data into a PDF.

Component.ts

public getReports(type?: string): void {
    this.params['expected-format'] = type;

    if (type === 'json') {
      this.Service.getPilotReports(this.params).subscribe((res) => {
        this.reportsData = res;
        this.pilotBankSpinnerService.closeSpinner();
      });
    } else {
      this.Service.customGetForDownload(this.params).subscribe(
        (data: Blob) => {
          var file = new Blob([data], { type: 'application/pdf' });
          var fileURL = URL.createObjectURL(file);
          window.open(fileURL);
          var a = document.createElement('a');
          a.href = fileURL;
          a.target = '_blank';
          a.download = 'reports.pdf';
          document.body.appendChild(a);
          a.click();          
        },
        (error) => {
          console.log('getPDF error: ', error);
         
        }
      );
    }
}

Service.ts

public customGetForDownload<blob, T>(url: string, params: any): any {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json', responseType: 'blob' });
    const httpParams = this.http.constructParams(params);
    const absoluteUrl = this.getAbsoluteUrl(url);
    return this.httpClient.get(absoluteUrl, {
      headers: headers,
      params: httpParams,
      responseType: 'blob' as 'json',
      observe: 'response',
    });
}

Though the file is getting saved. When I try to open the file, it says "Failed to load pdf document".

Source: Angular Questions

Published
Categorized as angular, java, spring-boot Tagged , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq