I have a response from an API in the form of a binary file and I need to transform it into a PDF in react.js

39 views Asked by At

I've been trying everything but I can't generate the PDF properly; either I get a blank PDF or a text file with gibberish characters.

`try { const response = await getFunc(getUrl, token, header);

  const url = window.URL.createObjectURL(new Blob([response]));

  // Crear un enlace para descargar el PDF
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "miArchivo.pdf"); // Cambiar a .pdf
  document.body.appendChild(link);
  link.click();

  // Limpieza después de la descarga
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
} catch (error) {
  console.error("Error al descargar el certificado:", error);
}`

I need the PDF file

By the way, this is how the API give me the PDF.

Postman View of the response: Postman

Postman headers that came with the file: Headers

1

There are 1 answers

6
PassThru On

Try this instead...

try{

 let response = getFunc(getUrl, token, header);

 let blob=new Blob([response],{type:"application/pdf"});

 let url = URL.createObjectURL(blob);

 let link = document.createElement('a');

 link.target = '_blank';

 link.href = url;

 link.download='miArchivo.pdf';

 link.click();

 setTimeout(function(){URL.revokeObjectURL(url);},3000);

} catch(e){alert(e);}

NB: Script assumes your getFunc() which you haven't posted, works like a charm.