这是下载pdf文件在角度2的功能,当我下载Pdf文件,它是损坏的文件。那么我该如何解决这个问题呢?它会像这样显示损坏的数据。%PDF-1.5%obj 66 0 obj <>内部对象
downloadFile() {
//this.http.get('https://contactsapi.apispark.net/v1/companies/').subscribe(
this.http.get('assets/Files/booking.pdf').subscribe(
(response: any) => {
console.log(response);
let parsedResponse =(response)
var blob = new Blob([response], {type: 'application/pdf'});
var filename = 'booking.pdf';
saveAs(blob, filename);
});
}发布于 2017-08-22 19:29:13
我们需要这个包文件-保护程序,你像一样安装“npm install file--saver--保存”,然后你可以这样尝试。
public downloadCSVFile(){
this.downloadPdf().subscribe(
(res) => {
saveAs(res,'test.pdf')
}
);
}
public downloadPdf(): any {
let url='your url'
let headers = new Headers();
headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
return this.http.get(url,{ headers: headers,responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
})
}发布于 2018-12-10 20:51:21
在Angular 6中,在服务downloadPdfFile.service.ts中创建以下内容。
导入语句
import {
HttpClient,
HttpHeaders
} from '@angular/common/http';
import { map } from 'rxjs/operators';下载pdf的方法
downloadPDF(dataObj) {
let headerOptions = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/pdf'
// 'Accept': 'application/octet-stream', // for excel file
});
let requestOptions = { headers: headerOptions, responseType: 'blob' as 'blob' };
// post or get depending on your requirement
this.http.post(serviceURL, dataObj, requestOptions).pipe(map((data: any) => {
let blob = new Blob([data], {
type: 'application/pdf' // must match the Accept type
// type: 'application/octet-stream' // for excel
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'samplePDFFile.pdf';
link.click();
window.URL.revokeObjectURL(link.href);
})).subscribe((result: any) => {
});
}组件文件只需调用方法
downloadPdf()
{
let dataObj={}
this.downoloadPdfFileService.downloadPDF(dataObj);
}发布于 2019-09-20 17:59:34
如果你想要一个简单的解决方案,试试这个:
<a download="b82d8486-a931-421c-b594-f4d3129746e5.pdf" target="_blank" href="/assets/files/b82d8486-a931-421c-b594-f4d3129746e5.pdf">
Download pdf
</a>https://stackoverflow.com/questions/45815864
复制相似问题