我正在尝试从Web API获取PDF文档,并希望在Angular App中显示。获取"无法加载PDF文档错误"。
请关注我的代码:
我的服务。
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())
}
我的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>
结果是:下载test.pdf - &gt;错误无法加载PDF文档。
答案 0 :(得分:0)
请按照以下步骤解决此问题。
第1步。如下所示,将字节数组转换为API中的base64字符串
[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;
}
}
第2步。添加下面的函数,以将base64字符串转换为.ts文件中的ArrayBuffer
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;
}
第3步。在自定义函数中为按钮单击事件调用step2函数
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)
});
答案 1 :(得分:0)
您也可以在 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;
}