Raj Shekhar Dev

Back

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.

  1. Download

    const response = await fetch(url);
    const fileBlob = await response.blob();
  2. If you want to convert local file

    let selectedFile = document.getElementById("inputFile").files;
    let fileBlob = selectedFile[0];
  3. Create a FileReader and convert to dataurl / base64 url

    const reader = new FileReader();
    reader.readAsDataURL(fileBlob);
  4. 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.