我试图从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())
}
我的组件
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 - >错误无法加载PDF文档。
请按照以下步骤解决此问题。
步骤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.添加以下函数以在.ts文件中从base64字符串转换为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)
});