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
🌐
Stack Overflow
stackoverflow.com › questions › 65725309 › javascript-how-to-convert-and-download-base64-pdf-data-as-an-png-image
Javascript - How to convert and download base64 pdf data as an png image? - Stack Overflow
var base64pdfData = atob( 'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwogIC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAvTWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0KPj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAgL1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9udAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2JqCgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtC
🌐
Pdfcoding
pdfcoding.com › pdf › javascript › convert-image
convert base64 pdf to image javascript
jspdf autotable drawcell, jspdf add image png, jspdf autotable center text, pdf to excel javascript, convert base64 pdf to image javascript, convert pdf to jpg using javascript, javascript convert pdf to tiff, javascript code to convert pdf to word, jquery pdf generator library, convert excel ...
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
PDF to Base64 | Base64 Encode | Base64 Converter | Base64
Hello, I am looking for a way to convert a pdf file to base64 in Javascript using FileReader. I have the path of the pdf file, but not able to convert to base64.
🌐
Stack Overflow
stackoverflow.com › questions › 34775399 › how-can-i-convert-a-base64-pdf-to-base64-jpg-jpeg
javascript - How can I convert a base64 pdf to base64 jpg / jpeg? - Stack Overflow
January 13, 2016 - these files already comes from ... jpg again ... why bother writing (or finding) a pdf reader that accepts b64 input? b64->binary is a pretty simple operation, and you'll have far better luck finding a b64->binary converter, ...
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Convert Base64 to PDF in JavaScript | Examples | JavaScript | Developers | Base64
Do you have a Base64 string and do not know how to convert it to PDF using JavaScript? Do not worry! I am here to help you. I will show you some practical examples how to decode Base64 to PDF using the atob function and get some information about it.
🌐
npm
npmjs.com › package › pdf-to-base64
pdf-to-base64 - npm
October 4, 2020 - Generate a pdf to base64. Latest version: 1.0.3, last published: 6 years ago. Start using pdf-to-base64 in your project by running `npm i pdf-to-base64`. There are 21 other projects in the npm registry using pdf-to-base64.
      » npm install pdf-to-base64
    
Published: Oct 04, 2020
Version: 1.0.3
🌐
Stack Overflow
stackoverflow.com › questions › 35034927 › convert-a-base64-into-an-image-in-javascript
Convert a Base64 into an image in javascript - Stack Overflow
var html = "<img src='data:image/png;base64," + base64_string + "'>"; document.body.appendChild( html ); also you need to put this code in the onload event of the reader api
Find elsewhere
🌐
GitHub
github.com › yakovmeister › pdf2image
GitHub - yakovmeister/pdf2image: A utility for converting pdf to image and base64 format. · GitHub
The parameter can also be a boolean, if true then the response type will be base64 and if false then the response type will be image.
Author: yakovmeister
🌐
GitHub
github.com › ShubhamBansal1997 › pdf-to-base64
GitHub - ShubhamBansal1997/pdf-to-base64: Convert pdf from file or url to base64 · GitHub
It was all about converting the pdf into base64 string ... const pdf2base64 = require('pdf-to-base64'); pdf2base64("test/sample.pdf") .then( (response) => { console.log(response); //cGF0aC90by9maWxlLmpwZw== } ) .catch( (error) => { console.log(error); //Exepection error.... } ) const pdf2base64 = require('pdf-to-base64'); pdf2base64("http://www.africau.edu/images/default/sample.pdf") .then( (response) => { console.log(response); //cGF0aC90by9maWxlLmpwZw== } ) .catch( (error) => { console.log(error); //Exepection error....
Author: ShubhamBansal1997
🌐
Yiigo
yiigo.com › pdf › javascript › create-image
convert base64 image to pdf javascript
jspdf autotable drawcell, jspdf image align right, jspdf text wrap, convert pdf to excel using javascript, pdf to image using javascript, convert pdf to jpg using javascript, javascript convert pdf to tiff, javascript code to convert pdf to word, javascript pdf generator open source, convert ...
🌐
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 ...
Top answer
1 of 2
1

To receive the base64 value in the getPDF function you can use promises.

getPDF() {
    let image = "assets/icon/logo.png";
    this.getBase64Image(image).then(imageData => {
       console.log("imageData", imageData);
    }).catch(err => {
        console.log(err);
    });

}

getBase64Image(img) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", img, true);
        xhr.responseType = "blob";
        xhr.onload = function (e) {
          console.log(this.response);
          var reader = new FileReader();
          reader.onload = function (event) {
            resolve(event.target["result"]);
          }
          reader.onerror = function(e) {
             reject(e);
          };
          var file = this.response;
          reader.readAsDataURL(file)
        };
        xhr.onerror = function (e) {
            reject(e);
        }
        xhr.send();
    });    
}
2 of 2
1

As suggested by @abadalyan, return a Promise from your getBase64Image.

Also do not forget to check the status of the response with readyState and status and handle any errors using XMLHttpRequest.onerror and XMLHttpRequest.ontimeout using the reject callback of the Promise.

You also have to check the FileReader errors with FileReader.onerror and FileReader.onabort, or you could use the FileReader.loadend callback instead of FileReader.load to make sure the promise always resolves even when you get a read error.

Here is an example with error handling:

function getBase64Image(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const reader = new FileReader();
        reader.readAsDataURL(xhr.response);
        reader.onerror = e => reject(new Error('Reading error.', e));
        reader.onabort = e => reject(new Error('Reading abort.', e));
        reader.onload = () => resolve(reader.result);
      } else {
        reject(request.statusText);
      }
    };
    xhr.onerror = e => reject(new Error('Network error.', e));
    xhr.ontimeout = e => reject(new Error('Timeout error.', e));
    xhr.send();
  });
}

getBase64Image('https://cors-anywhere.herokuapp.com/https://loremflickr.com/100/100').then(image => {
  console.log(image);
  document.querySelector('#img1').src = image;
}).catch(e => console.error(e.message || e));
  
getBase64Image('wrong-url').then(image => {
  console.log(image);
  document.querySelector('#img2').src = image;
}).catch(e => console.error(e.message || e));
<img id="img1" src="" alt="No image yet">
<img id="img2" src="" alt="No image yet">

🌐
OutSystems
outsystems.com › forums › discussion › 66463 › mobile-base64-pdf-file-to-image
Mobile Base64 pdf file to Image | OutSystems
November 20, 2020 - I am trying to build a client action for an offline mobile application, the goal is to convert the local storage Base64 pdf file to an Image. I am trying to convert the data since I will be using the Image widget · Here is what I have done
🌐
JSFiddle
jsfiddle.net › pdfjs › pdf.js 'hello, base64!' example
PDF.js 'Hello, base64!' example - JSFiddle - React, Tailwind, and code Playground
October 10, 2023 - <script src="//mozilla.github.io/pdf.js/build/pdf.mjs" type="module"></script> <script type="module"> // atob() is used to convert base64 encoded PDF to binary-like data.
Published: Oct 10, 2023
Author: pdfjs
🌐
freeCodeCamp
freecodecamp.org › news › save-a-base64-string-as-pdf-on-client-side-in-javascript
How to Save a Base64 String as a PDF File on the Client Side in JavaScript
February 27, 2023 - Sometimes, you might receive PDF files from various services as a Base64 string, and you may need to convert them to a PDF file on the client side after receiving the response. This tutorial teaches you how to save a Base64 string as a PDF on the client side in JavaScript.
🌐
Base64.Guru
base64.guru › converter › decode › image
Base64 to Image | Base64 Decode | Base64 Converter | Base64
The “Base64 to Image” converter will force the decoding result to be displayed as an image, even if it is a different file type. Therefore, if you are not sure that your Base64 string is an image, use the Base64 to file converter since it is capable of displaying various file types.
🌐
Craftmypdf
support.craftmypdf.com › using a base64 image in a pdf
Using a base64 image in a PDF | CraftMyPDF Documentation
(i) Make(Formerly Integromat): Use the string function base64 to convert an image to a base64 string. (ii) Zapier: Use Javascript or Python code to convert an image to a base64 string