Reputation: 248
I am trying to get PDF document from Web API, and want to show in Angular App. Getting "Failed to load PDF document error".
Please follow my code:
My service.ts
public download_pdf(id: string): Observable<any> {
let params = new URLSearchParams();
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
headers.append('id', id);
return this.http.get(Api.getUrl(Api.URLS.download_pdf), {
headers: headers,
responseType: ResponseContentType.ArrayBuffer,
}).map(
response => (<Response>response).blob())
}
My component.ts
downloadFile2(id) {
this.ws.download_pdf(id).subscribe(
(response) => {
let mediaType = 'application/pdf';
let blob = new Blob([response._body], {type: mediaType});
let filename = 'test.pdf';
FileSaver.saveAs(blob, filename);
});
}
Template.html
<button>
<i class="fa fa-save" aria-hidden="true"(click)="downloadFile2(item.id)"></i>
</button>
Result is: download a test.pdf --> Error Failed to load PDF document.
Upvotes: 1
Views: 8398
Reputation: 229
You can use this also in Angular 10.
getPdf():Observable<any> {
return this.http.get<any>(`${this.apiUrl}Controller/GetPdf`);
}
this.service.getPdf().subscribe((resp) => {
let response = this.base64ToArrayBuffer(resp);
let file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
}
base64ToArrayBuffer(base64:any):ArrayBuffer {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
Upvotes: 1
Reputation: 123
Follow the below steps to resolve the issue.
Step 1. Convert your byte array to base64 string in your API like below
[HttpGet("Downloadpdf/{SessionKey}")]
public IActionResult Downloadpdf(string SessionKey)
{
Byte[] pdf = null;
try
{
pdf = PDFService.Downloadpdf(SessionKey);//Here you need to modify and get byte array like byte[]
string pdfBase64 = Convert.ToBase64String(pdf);
return Ok(pdfBase64);
}
catch (Exception ex)
{
throw ex;
}
}
step 2. Add a below function to convert from base64 string to ArrayBuffer in .ts file
base64ToArrayBuffer(base64:any):ArrayBuffer {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
step 3. Call step2 function in your custom function for button click event
let sessionKey: any ="sessiontoken";
this.pdfService.downloadpdf(sessionKey).subscribe((data: any) => {
var byteArray = this.base64ToArrayBuffer(data);
let blob: any = new Blob([byteArray], { type: 'application/octet-stream' });
saveAs(blob, 'Report.pdf',true);
},
(error: HttpErrorResponse) => {
console.log(error)
});
Upvotes: 2