1

I have a very simple REST service written in Java:

@RequestMapping(path="/getPdf", method=RequestMethod.GET)
    public ResponseEntity<byte[]> getPdf() throws IOException {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("sample/CleanCode.pdf");
            
    // At this point, the PDF file exists and weigths around 3.7Mb
    return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), HttpStatus.OK);
}

Which I call from Angular 10:

document.service.ts:

getPdf(): Observable<Uint8Array> {
    // Fetches correctly
    return this.http.get<Uint8Array>(`${this.url.document}${this.getPdfUrl}`);
}

To display in another tab, which should be very straightforward:

main.component.ts:

this.documentService.getPdf().subscribe(pdfContent => {
    // 1st strange thing: pdfcontent.byteLength gives 5Mb instead of 3,7Mb
    const file = new Blob([pdfContent], { type: 'application/pdf' });

    const fileURL = URL.createObjectURL(file);
    window.open(fileURL);
});

This opens a new tab with a temporary blob:

// For instance
blob:http://localhost:4200/2aff6007-8f16-45d3-84a1-1bd0dff2eab9

And it does not work. It gives us a popup "Failing to load PDF document". I tried a lot of things from various questions, without success (here or here for instance).

Can anyone help me finding why my existing, valid PDF file becomes invalid / corrupted after passing through a REST call ? Does it have something to do with headers, or a missing configuration somewhere ?

Thanks in advance;

Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
  • Have you tried setting the Content-Type response header to application/pdf server side ? When you examine the response in Angular, does it look like what a raw pdf looks like ? have you tried with other HTTP clients (eg postman) ? – Chris Neve Jun 21 '21 at 13:03
  • I tried `application/octet-stream` as it is sent as a byte[], but I may try `application/pdf`. I examined the response as it was, an array of bytes, can I see what it could look like through the `network` tab ? Postman sends the same byte of array. I can't send it as an attachment, by the way. – Yassine Badache Jun 21 '21 at 13:06

0 Answers0