1

I am working on angular12, via api i get pdf data, i am converting that data to arrayBuffer via method below:

getArrayBuffer(url: string, queryParams: HttpParams = new HttpParams()): Observable<any> {
    this.spinner.show();
    return this.http
      .get(`${environment.serverUrl}${url}`, {
        responseType: 'arraybuffer',
        params: queryParams,
      })
      .pipe(
        map((result: any) => {
          return result;
        })
      )
      .pipe(map(this.handleGetResponse.bind(this)))
      .pipe(catchError(this.handleError.bind(this)));
  }

now, this is getting converted to base64, so that i can show it back as pdf file with below method: enter image description here

so the param passing as buffer to arrayBufferToBase64 method is the data shown in above image.

  arrayBufferToBase64(buffer: any) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        bytes.forEach((item:any) => {
          binary += String.fromCharCode(item);
        });
        // for (var i = 0; i < len; i++) {
        //   binary += String.fromCharCode(bytes[i]);
        // }
        return window.btoa(binary);
      }

as the data is huge, after 1 minute or so the browser shows a popup to kill or wait page, is there any way wherein i can fast render the data

Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88
  • May i ask what's the ultimate goal, do you want the base64 to construct a data: URI to show the PDF in the browser? I guess that won't work very well, likely you want to change responseType to "blob" and then use URL.createObjectURL() – diegocr May 28 '23 at 22:28

1 Answers1

0

You can use built-in btoa() function.

function arrayBufferToBase64(buffer: ArrayBuffer): string {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}
Souvik
  • 32
  • 5