In the process of developing a web application using Angular 9, there is a requirement from the client that a PDF should be downloaded upon submitting a form on a particular page.
The backend (server-side) is able to generate the PDF file successfully and return it as a stream. The response from the Web API developed can be viewed at the following link:
Various methods were attempted in the Angular app to either open the PDF in the browser or download it as a file. However, the result obtained was similar to what is shown in the screenshot below:
https://i.sstatic.net/YKGMF.png
The first method involved:
loadReport(){
this.spinner.show();
//////// /////////////// /////////////////////
this.api.loadReport(this.filterVM)
.subscribe(res => {
console.log(res);
this.spinner.hide();
////// //////////////////////////
const blob = new Blob([res], { type: 'application/pdf' });
const url= window.URL.createObjectURL(blob);
window.open(url);
////////// /////////////////////
}, err => {
console.log(err);
this.spinner.hide();
});
///// ///////////// //////////////////////////
}
The second approach utilized:
loadReport(){
this.spinner.show();
//////// /////////////// /////////////////////
this.api.loadReport(this.filterVM)
.subscribe(res => {
console.log(res);
this.spinner.hide();
////// //////////////////////////
this.saveByteArray("Sample Report.pdf", res);
////////// /////////////////////
}, err => {
console.log(err);
this.spinner.hide();
});
///// ///////////// //////////////////////////
}
saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
};
The outcome of the second methodology is depicted in the provided screenshot:
https://i.sstatic.net/edluj.png
Upon attempting to download the file, it was noticed that the actual size of the file is significantly lesser than the size indicated in the HTTP response (9 bytes vs ~16 KB).
The headers sent in the Web API HTTP response include:
Content-Type: application/pdf
Content-Length: 16187
Content-Disposition: attachment; filename=Report.pdf; filename*=UTF-8''Report.pdf
Several blogs and sites have been referenced for potential solutions, however, none have yielded success yet.
Download File from Bytes in JavaScript
Typescript blob filename without link
https://dev.to/nombrekeff/download-file-from-blob-21ho
How do I download a file with Angular2 or greater