To Download the PDF from the URL in NEXT JS

We are passing the file details, including the size and URL, to the function.

  //Function that allows downloading files
  const handleDownloadFile = (file) => {
    const xhr = new XMLHttpRequest();
      const PDFurl='https://'+file.fileUrl;
      const PDFActual = PDFurl.replace("app", 'extforms');
      xhr.open('GET', PDFActual, true);
      xhr.responseType = 'blob';


      xhr.onload = function () {
        if (xhr.status === 200) {
          // Create a link element
          const link = document.createElement('a');


          // Create a Blob from the response
          const blob = new Blob([xhr.response], { type: 'application/pdf' });


          // Set the download attribute with the desired file name
          link.href = window.URL.createObjectURL(blob);
          link.download = file.fileName;


          // Append the link to the document
          document.body.appendChild(link);


          // Trigger a click event on the link to start the download
          link.click();


          // Remove the link from the document
          document.body.removeChild(link);
        } else {
          console.error('Error downloading PDF. Status:', xhr.status);
        }
      };
    xhr.send();
  };

Leave a comment

Your email address will not be published. Required fields are marked *