Try this :-

<input id="inputFile" type="file" onchange="convertToBase64();" />

<script type="text/javascript">
    function convertToBase64() {
        //Read File
        var selectedFile = document.getElementById("inputFile").files;
        //Check File is not Empty
        if (selectedFile.length > 0) {
            // Select the very first file from list
            var fileToLoad = selectedFile[0];
            // FileReader function for read the file.
            var fileReader = new FileReader();
            var base64;
            // Onload of file read the file content
            fileReader.onload = function(fileLoadedEvent) {
                base64 = fileLoadedEvent.target.result;
                // Print data in console
                console.log(base64);
            };
            // Convert data to base64
            fileReader.readAsDataURL(fileToLoad);
        }
    }
</script>

Answer from Mohit Singh on Stack Overflow
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
PDF to Base64 | Base64 Encode | Base64 Converter | Base64
Convert PDF to Base64 online and use the result string as data URI, HTML object, and others. Sometimes you have to send or output a PDF file within a text document (for example, HTML, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document.
🌐
npm
npmjs.com › package › pdf-to-base64
pdf-to-base64 - npm
October 4, 2020 - Generate a base64 from pdf path or url. It was all about converting the pdf into base64 string
      » npm install pdf-to-base64
    
Published: Oct 04, 2020
Version: 1.0.3
People also ask

How do I convert a PDF to Base64?
Drop the PDF onto the converter on this page. It reads the file locally with the FileReader API and outputs raw Base64 by default. Toggle Data URI to get the data:application/pdf;base64,... form instead. Click Copy to grab the result.
🌐
base64.dev
base64.dev › home › pdf to base64
PDF to Base64 Converter — base64.dev
Is it safe to convert a PDF to Base64 online?
On base64.dev, yes — the conversion runs entirely in your browser with JavaScript. The PDF is never uploaded to any server, so even confidential or sensitive documents stay on your machine.
🌐
base64.dev
base64.dev › home › pdf to base64
PDF to Base64 Converter — base64.dev
How much bigger is a PDF after Base64 encoding?
Base64 is about 33% larger than the original binary. A 5 MB PDF becomes roughly 6.7 MB of text. That overhead is fine for transport in JSON or email, but watch out for database column size limits when storing it.
🌐
base64.dev
base64.dev › home › pdf to base64
PDF to Base64 Converter — base64.dev
🌐
Stack Overflow
stackoverflow.com › questions › 70684776 › encoding-a-remote-url-pdf-to-base64-javascript
Encoding a remote URL PDF to BASE64 (javascript) - Stack Overflow
readAsDataURL can't be used to read from a remote URL, but is made for data in form of a so called Data URI, e.g data:application/pdf;base64,JVBERi0xLjQKJe..., in which the data is already embedded as base64 string.
🌐
Stack Overflow
stackoverflow.com › questions › 36744743 › how-can-we-convert-pdf-of-url-to-convert-tobase64string-in-javascript
How can we convert PDF of URL to Convert.ToBase64String in javascript - Stack Overflow
May 22, 2017 - Copy// create base 64 encoded string var PDFContentBase64 = btoa(unescape(encodeURIComponent(PDFAsString)))); var pdfdiv = document.getElementById("getpdf");` pdfdiv.innerHTML = "<h3><a title=\"View PDF file\" href=\"data:application/pdf;base64,' ...
🌐
Stack Overflow
stackoverflow.com › questions › 57218864 › jquery-how-to-convert-url-based-pdf-file-to-base64-and-download-it
html - jquery - how to convert url based pdf file to base64 and download it - Stack Overflow
Copy<script> var url = "https://www.tutorialspoint.com/html/html_tutorial.pdf"; function convert(url){ $.ajax({ url: url, type: "get", success: function(res){ var file = btoa(unescape(encodeURIComponent(res))); var nfile = "data:application/octet-stream;base64," + decodeURIComponent(escape(file)); var dlnk = document.getElementById('download'); dlnk.href = nfile; dlnk.click(); } }); } </script>
🌐
Base64
base64.dev › home › pdf to base64
PDF to Base64 Converter — base64.dev
August 13, 2026 - Payload bloat: a Base64 PDF inflates request sizes and memory use; for large or frequently reused files, an upload + URL reference is usually better. Tip: Base64 size is predictable — roughly ceil(bytes / 3) * 4 characters. Use it to sanity-check against your column or payload limits before you commit. Yes. The conversion happens entirely client-side in JavaScript.
Find elsewhere
🌐
Medium
medium.com › @simmibadhan › converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
Converting file to base64 on Javascript client side | by Simmi Badhan | Medium
July 1, 2020 - // Convert file to base64 string export const fileToBase64 = (filename, filepath) => { return new Promise(resolve => { var file = new File([filename], filepath); var reader = new FileReader(); // Read file content on file loaded event reader.onload ...
🌐
Stack Overflow
stackoverflow.com › questions › 74548412 › convert-pdf-url-to-base64-error-when-open-file
javascript - Convert PDF url to Base64, error when open file - Stack Overflow
November 23, 2022 - just maybe(!! I'm not sure) developer.mozilla.org/en-US/docs/Web/API/FileReader/… Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data.
🌐
SurveyJS
surveyjs.io › pdf-generator › examples › convert-pdf-form-blob-base64-raw-pdf-javascript › documentation
Convert PDF Form to Blob, Base64 URL, or Raw PDF | SurveyJS PDF Form Builder
To export a PDF document as a Blob or Blob URL, pass "blob" or "bloburl" to the raw(type) method of a SurveyPDF instance: ... This demo uses a Blob to display a preview of a survey PDF file. A Base64 Data URL is a string that contains Base64-encoded binary data preceded by the word data, an MIME type that indicates the data type, and an optional base64 prefix for non-textual data.
🌐
FileFlow Tool
base64-to-image.com › home › pdf tools › pdf to base64
PDF to Base64 Converter – Copy Data URL or JSON
Select a PDF and generate raw Base64, a complete PDF data URL, formatted JSON or a JavaScript download snippet. The encoding preserves the original PDF bytes so the result can be decoded back to the same file.
Author: ShubhamBansal1997
Top answer
1 of 2
1

Worried that none of answer mentioned here has pointed this out, I am saying this:

File objects may be obtained from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation's DataTransfer object. Source

Therefore only a code like below will work:

const fileInput = document.getElementById("fileInput");
const output = document.getElementById("output");

// Event listener when a user selects a file
fileInput.addEventListener("change", function(event) {
  const file = event.target.files[0]; // Get the selected file

  if (file && file.type === "application/pdf") {
    const reader = new FileReader();

    // Read the file as a Data URL (Base64)
    reader.readAsDataURL(file);

    reader.onload = function() {
      const base64String = reader.result; // Base64 string
      output.textContent = base64String.split(",")[1]; // Display Base64 data (without prefix)
      console.log("Base64 PDF String:", base64String);
      alert(base64String); // as stackoverflow console doesn't display 
      alert("See your browser console as well(not the SO console that will come below empty due to overflow/styling)")
    };

    reader.onerror = function(error) {
      console.error("Error reading file:", error);
    };
  } else {
    alert("Please select a valid PDF file.");
  }
});
<h1>Select a PDF File to Read</h1>
<input type="file" id="fileInput" accept="application/pdf" />
<pre id="output"></pre>

Leo's answer will result in Uncaught TypeError: Failed to construct 'File': The provided value cannot be converted to a sequence. as xRdev said

xRdev's answer

var file = new File(["foo"], "/pdf/test.pdf", {type: 'application/pdf'});

creates a new empty file with just content "foo" inside it, simulating that it is stored in path "/pdf/test.pdf" so eventhough you get base64 it doesnt look like
data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAws2... but instead as data:application/pdf;base64,zsfasf

2 of 2
-2

With fileReader you can convert your file from path like this :

var file = new File("/pdf/test.pdf","r");

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}
🌐
SurveyJS
surveyjs.io › pdf-generator › examples › convert-pdf-form-blob-base64-raw-pdf-javascript › reactjs
Save PDF Form as a File, Raw PDF, Blob, or Base64 URL | JavaScript Example
Besides being able to download fillable survey forms as document files in a traditional PDF format, you can get them in other formats as well. These formats are mainly used to display PDF content in HTML inline, transfer PDF forms over the web, or store them in a database. This example shows how to get raw PDF content or convert it to Blob or a Base64-encoded data URL.
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Convert Base64 to PDF in JavaScript | Examples | JavaScript | Developers | Base64
My JavaScript Base64 Polyfill adds Base64 support even for Internet Explorer 5. ... This is a very helpful code that you provided here and thanks for it. I have a question related to my implementation. I want to show a pdf file into Salesforce using base64 data in the JS.
Top answer
1 of 3
114

from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js

/**
 * This is the main entry point for loading a PDF and interacting with it.
 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
 * is used, which means it must follow the same origin rules that any XHR does
 * e.g. No cross domain requests without CORS.
 *
 * @param {string|TypedAray|object} source Can be an url to where a PDF is
 * located, a typed array (Uint8Array) already populated with data or
 * and parameter object with the following possible fields:
 *  - url   - The URL of the PDF.
 *  - data  - A typed array with PDF data.
 *  - httpHeaders - Basic authentication headers.
 *  - password - For decrypting password-protected PDFs.
 *
 * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
 */

So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).

But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746

var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

tl;dr

var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
2 of 3
4

According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.