'Failed to load PDF document - Angular 8
I am trying to open a PDF in another browser tab using Angular 8. The PDF is returned by a Spring boot API as a byte array:
@GetMapping(value = "/pdf")
public ResponseEntity<byte[]> beve(HttpServletRequest request) {
return new ResponseEntity<byte[]>(service.getPdf(request), HttpStatus.OK);
}
On the Angular side, for the service:
getPdf(): any {
const httpOptions = {
'responseType' : 'arraybuffer' as 'json'
};
return this.http.get<any>(this.url + "/pdf", httpOptions);
}
And the component that is calling it:
getPdf() {
this.service.getPdf().subscribe((response => {
const file = new Blob([response], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, "app.pdf");
} else {
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}));
}
However, when the PDF opens up in a new tab, I get this error:
What am I doing wrong?
Thanks
Solution 1:[1]
I have also faced similar situation. try converting array buffer into base64 string and it is working fine in all browsers.
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(data.data)));
var pdfAsDataUri = "data:application/pdf;base64," + base64String;
windoe.open(pdfAsDataUri);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sainanky |

