Search code examples
reactjsnestjs

SOLVED - How to open Streamable File as pdf in React client


I got this data from backend when try to get a pdf file:

`%PDF-1.7 %���� 5 0 obj <</Filter/FlateDecode/Length 823>>stream x���MS�0���{l���)&���#CCK'!%�ӿߕmb���;�y�Ҿ��K��H�����aN��q��%�Iz&@�i�T
<......>
1950
%EOF\`

How can REACT read and open this as pdf file in a new tab? NOTE: I'm able to see the PDF file content in postman when call backend endpoint.

I tried this:

Backend controller (Nestjs):

  @Get('/getPDF/:uuid')
  async getFile(
    @Param('uuid') uuid: string,
    @Response({ passthrough: true }) res,
  ): Promise<StreamableFile> {
    const resp = await this.service.downloadPDF(uuid);

    if (!resp) {
      return null;
    }

    res.header('Content-Type', `application/pdf`);
    res.header('Content-Disposition', `attachment; filename="${resp.fileName}`);
    return new StreamableFile(resp.buffer); // resp.buffer === Uint8Array
  }

Frontend (REACT):

This will call backend api to get pdf file:

  getPDF(uuid: string): Promise<AxiosResponse<Blob>> {
    return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
      responseType: 'blob',
    });
  }

This was supposed to render the pdf file

const response = await api.getPDF(uuid);
window.open(URL.createObjectURL(response.data));

I got this error:

TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.


UPDATED

Change AxiosResponse type from Blob to ArrayBuffer and create a new Blob from that buffer, solves the issue

This works:

  getPDF(uuid: string): Promise<AxiosResponse<ArrayBuffer>> {
    return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
      responseType: 'arraybuffer',
    });
  }
const response = await api.getPDF(uuid);
const blob = new Blob([response.data], { type: "application/pdf" });
window.open(URL.createObjectURL(blob));

Thanks amir sarfar


Solution

  • Try passing a blob to createObjectURL:

    
    const response = await api.getPDF(uuid);
    const blob = new Blob([response.data], { type: "application/pdf" });
    window.open(URL.createObjectURL(blob));