How to convert string Base64 to pdf in angular 7
If I understood that right, the backend sends back base64 encoded data. So, you have to decode the response data first. The workflow should look like this:
fetch(fileUploaded.content)
.then(response => {
// response.data -> response data base64 encoded
// decoding the data via atob()
const byteArray = new Uint8Array(atob(response.data).split('').map(char => char.charCodeAt(0)));
return new Blob([byteArray], {type: 'application/pdf'});
})
.then(blob => {
// Here is your URL you can use
const url = window.URL.createObjectURL(blob);
// i.e. display the PDF content via iframe
document.querySelector("iframe").src = url;
});
Further you can read about
- Creating a Blob from a base64 string in JavaScript
atob()
Edit:
if i want to display the pdf result in my html using . do you have any idea how to do it. thanks in advance
Here is an example how you achieve this: https://stackblitz.com/edit/angular-rwfdhr
Notes:
Unfortunately I couldn't make
ngx-extended-pdf-viewer
work on stackblitz.com. Maybe you can give it a try in your environment. I didn't try it locally. Instead I usedpdf-viewer
and it just worked out-of-the-box. But I don't see any reason why it shouldn't work with another library, because the workflow has the same principle.My solution is based on my previous answer. Since I don't know your code base exactly, I've done things the way I understood your workflow:
There is a service called
PdfService
(see pdf.service.ts) I created, which basically fetches and returns the base64 encoded PDF content from GitHub Gist that I just created.In the class
AppComponent
(app.component.ts) the base64 content is decoded and converted to blob and that to aDOMString
URL (viaURL.createObjectURL
).In app.component.html this URL is simply passed to the library for further processing.
Edit 2: The above example does not fit perfectly to Angular way. You should implement the business logic in the services, and keep the controllers as lean as possible.
Here's a demo: https://stackblitz.com/edit/angular-4k63jv
I think this would work.
showPdf() {
const linkSource = 'data:application/pdf;base64,' + ' JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9Db2xvclNwYWNlL0';
const downloadLink = document.createElement("a");
const fileName = "sample.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}