[Fixed] Convert pdf URL to Base64


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.onload = () => {

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



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: [...,

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);


Leave a Reply

(*) Required, Your email will not be published