Fatih
Fatih

Reputation: 119

How can i download a pdf file that comes from a .NET Api with React?

enter image description here

I have a CreatePdf function on my Api an it returns a pdf file.When ı click a download button on a react page, it send a request to this function and trigger it.I can see the response like this image.But I could not manage to download it when I click the button. Also if i open this response on a new blank page, it automatically download the pdf.But I can not download it with button.

Upvotes: 1

Views: 1051

Answers (2)

IAMNITESHPANDIT
IAMNITESHPANDIT

Reputation: 59

const getPdfDownload = () => {
const url = "YOUR_URL";
axios
  .get(url, {
    responseType: "arraybuffer",
    headers: {
      Authorization: sessionStorage.getItem("AUTH_TOKEN") || "",
      "Content-Type": "application/json",
      Accept: "application/pdf",
    },
  })
  .then((response:any) => {

    const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'FILENAME.pdf');
        document.body.appendChild(link);
        link.click();
  }).catch((err)=>{
    console.log("Error", err);

  })

};

Upvotes: 0

sms
sms

Reputation: 1440

You can use anchor tag with download option..

<Button> 
<a href={"download pdf link"} download="PdfFileName">
   Download
 </a>
</Button>

Upvotes: 1

Related Questions