How to convert PDF file to base64 string in ionic

Hello All,

im looking for a way to convert PDF File to base64 string .

i have tried with the ionic base64 plugin which works on Android but for for IOS.

i have also tried the below file plugin

this.file.readAsDataURL(“filepath”, fileName).then(

                          file64 => {
                            console.log('file in 64: ', file64);
                             this returns  == data:application/pdf;base64
                          
                          }).catch(err => {
                          console.log('booooooo');
                        });

filepath looks like this == “file:///Users/venkatswamydandaboina/Library/Developer/CoreSimulator/Devices/9A8C76B7-F443-409E-8B62-377E7713DB67/data/Containers/Data/Application/D1AD60AE-D75C-4065-8B44-32470A3DA5DA/Library/NoCloud/”

but it doesnt returns base64 string it only returns “data:application/pdf;base64”.

Please help me out.
Thanks

Hey ashokdandaboina. Did you manage to convert pdf to base64?

Can anybody here explain why they want to do this?

It would be easier if we have the base64 format. I need it because I want to upload it to my server via REST API along with other parameters in the registration form

I don’t know why this misconception is so persistent and widespread.

Ever since the infancy of the web, the multipart/form-data content type has supported including binary data as part of a request. In modern times, FormData makes for very clean and straightforward code when doing this as an XHR POST, which is probably what you’re doing with it. The WebView will even handle setting Content-Type for you when you do this.

For people who still needs to do this i found the alternate workaround by using javascript input type file method
Below are the steps :
in html:

    <input accept="application/pdf"  #fileInput type="file" (change)="onFileChange($event)" />

in TS file :
triggering the input type file click event on a button do this:

@ViewChild(‘fileInput’) fileInputClick: ElementRef;

buttonClick() {

this.fileInputClick.nativeElement.click();
// this will open file chooser

}

// here the event gets triggered after selecting the pdf file

onFileChange(event) {

  console.log(event.target.files)
  var filename = event.target.files[0].name
  console.log("File Name")
  console.log(filename)
  var fileReader = new FileReader();
  fileReader.readAsDataURL(event.target.files[0])
  fileReader.onload = () => {
    console.log(fileReader.result)
   // here this method will return base64 string enjoy 

}

1 Like

Buenas, no se de cuando es esto, pero he probado el código incluso desde el filechooser y no entra al filereader. ¿Sabes como solucionarlo?

Muchas gracias

in index.html try loading cordova.js after polyfills.js and check .

<script src="build/polyfills.js"></script>
<script src="cordova.js"></script> //write this line after <script src="build/polyfills.js"></script>

In Spanish :slight_smile:
en index.html intente cargar cordova.js después de polyfills.js y verifique.

<script src = "build / polyfills.js"> </script>
<script src = "cordova.js"> </script> // escriba esta línea después de <script src = "build / polyfills.js"> </script>

Sorry i’m wrong to write in Spanish sorry,

Eh… no works. only i have the console.log out filename

http://localhost/tasks-task-register-task-register-module-es5.js - Line 1448 - Msg: [object FileList]
11-11 15:24:36.573 17537-17537 Capacitor/Console: File: http://localhost/tasks-task-register-task-register-module-es5.js - Line 1450 - Msg: File Name
11-11 15:24:36.573 17537-17537 Capacitor/Console: File: http://localhost/tasks-task-register-task-register-module-es5.js - Line 1451 - Msg: historia_escultura.pdf

Try this

 let fileReader = zoneOriginalInstance || newInstance;

 fileReader = new FileReader();
 fileReader.readAsDataURL(event.target.files[0])
 fileReader.onload = () => {
 console.log(fileReader.result)
 / / here this method will return base64 string enjoy 

}

2 Likes

Hi ashokdandaboina!!

THANK YOU VERY MUCH, you saved my day. I have 3 days making it works i did some changes but you gave me the start point thank you very much

I put my code if anybody need it too…

export function getFileReader(): FileReader {
const fileReader = new FileReader();
const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"];
return zoneOriginalInstance || fileReader;
}

onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
let newInstance = getFileReader();
newInstance.readAsDataURL(event.target.files[0]);
newInstance.onload = (imgsrc) => {
let url = (imgsrc.target as FileReader).result;
console.log(url)
}
}

1 Like

THANK YOOOOOOOOOOOUUUUUUUU FOR YOU CODE