Convert pdf URL to Base64

Viewed 5738

In my angular application, I used the below code for convert any file to Base64 string.

handleUpload(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
        console.log(reader.result);
    };
}

Here, I want to convert the pdf URL to base64 on the fly. Here's my sample URL which I want to convert base64.

https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf

2 Answers

You can use HttpClient to get the file from url. First you have to import HttpClientModule in app.module.ts

import { HttpClientModule } from '@angular/common/http';
imports: [...,
     'HttpClientModule',
       ...]

After that import in your component.ts HttpClient from '@angular/common/http' and add the instance in the constructor.

constructor(private http: HttpClient) { }

add the method

convertToBase64(url: string) {
    this.http.get(url, { responseType: "blob" }).subscribe(blob => {
      const reader = new FileReader();
      const binaryString = reader.readAsDataURL(blob);
      reader.onload = (event: any) => {
        //Here you can do whatever you want with the base64 String
        console.log("File in Base64: ", event.target.result);
      };

      reader.onerror = (event: any) => {
        console.log("File could not be read: " + event.target.error.code);
      };
    });
}
function getBase64(file) {
     return new Promise((resolve, reject) => {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result);
         reader.onerror = error => reject(error);
    });
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
   data => console.log(data)
);
Related