Convert pdf to base64
Let us assume the pdf is at url
. To convert this pdf to base64 we will download it as blob and the convert it to base64 url and then remove the url part of the base64 url.
-
Download
const response = await fetch(url); const fileBlob = await response.blob();
-
If you want to convert local file
let selectedFile = document.getElementById("inputFile").files; let fileBlob = selectedFile[0];
-
Create a FileReader and convert to dataurl / base64 url
const reader = new FileReader(); reader.readAsDataURL(fileBlob);
-
Remove the url part of base64 url
reader.onload = (evt) => { const base64data = evt.target.result.replace(/^data:.+;base64,/, ""); // do anything you want console.log(base64data); };
We are doing things inside the callback in reader.onload
because it takes time to download the pdf.