I'm trying to display a PDF with Typescript, it comes to me in base64 and I decode it to see the byte array.
The PDF opens, but blank, the pages match, but they are all without content.
I leave the content in base64 here PDF in Base64
Regarding the code I use to do it is the following.
In the service there is an API call, which is the one that returns the content.
getDescargaFactura(idFacturaVenta): Observable<any> {
const httpHeaders = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: this.token
});
const options = {
headers: httpHeaders
};
const body = { IdFactura: idFacturaVenta };
return this.http.post<any>(this.urlApi + 'Facturas/GetFacturasPDF', body, options);
}
And in the controller, I show the PDF.
descargaFactura(datos: any) {
this._facturasService
.getDescargaFactura(datos.IdFacturaVentaCabecera)
.subscribe(data => {
this.pdfFactura = this._funcionesService.decodificarToken(data);
const newBlob = new Blob([window.atob(this.pdfFactura.PDFBase64)], {
type: 'application/pdf'
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
const datos = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = datos;
link.download = 'file.pdf';
link.click();
});
}
I have done several tests and I can only display the PDF without content, I don't know if it is because of some coding issue or because of Angular itself.
The solution has been the following:
Change the response in the service. Adding the
Observable<Blob>
and the headerresponseType: 'blob' as 'json'
Once this has been modified, in the component, the service response has been added directly to the blob object
Also you have to add this import.
In the function that you have in the service you have to add the type of data that you want to collect.
In the function you have in the controller you have to add the file type. Also, I've added a few commented lines, suggesting you use the saveAS library.