问题
This is function to download pdf file in angular 2 when I am downloading Pdf file it is corrupted file. So how do I solve this problem. It is displaying corrupted data like this. %PDF-1.5 %���� ↵66 0 obj <> endobj
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);
});
}
回答1:
we need this package file-saver,you install like "npm install file-saver --save", then you can try like this
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' })
})
}
回答2:
Angular 6
downloadPdfFile.service.ts
import {
HttpClient,
HttpHeaders
} from '@angular/common/http';
import { map } from 'rxjs/operators';
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) => {
});
}
In component file just call the method
downloadPdf()
{
let dataObj={}
this.downoloadPdfFileService.downloadPDF(dataObj);
}
回答3:
If you want a simple solution, try this:
<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/how-to-download-pdf-file-in-angular-2