1

I am trying to download a PDF file that is returned by a POST request:
Here is my Angular method:

  sendPost: void {
  const options = {headers: {'Content-Type': 'application/json'}};
    this.http.post('http://localhost:8080/export', JSON.stringify(this.filter), 
    options )
      .subscribe((next) => console.log(next));
  }

And the Java backend that generates the PDF:

@CrossOrigin
@RequestMapping(value = "/export/", method = RequestMethod.POST)
public ResponseEntity<byte[]> getFilteredPDF(@RequestBody PdfExportFilter filter) throws IOException, DocumentException {
    StructureExporter writer = new FilteredPdfExporter(filter);
    Path filePath = Paths.get(writer.getBaseTempDir() + "/filteredExport.pdf");
    writer.exportData();
    return new ResponseEntity<byte[]>(readPdfBytes(filePath), getHttpHeaders("_filtered_export"), HttpStatus.OK);
}

How can I save the returned byte[] into a PDF file so it gets downloaded to the client?

Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
ItFreak
  • 2,299
  • 5
  • 21
  • 45

1 Answers1

1

You can use the data you get from the post and create, and follow this solution to create a downloadable file

Saving binary data as file using JavaScript from a browser

so the data should be the next from console.log(next)

in typescript it should be

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';

const blob = new Blob(next, {type: "octet/stream"}),
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36