Home > other >  React Display PDF from authenticated backend
React Display PDF from authenticated backend

Time:10-07

I have a React Frontend and Django Backend. In my frontend I want to include a view for the PDF obtained by the backend. I tried using iframe and object HTML Tags, but they failed due to the missing authentication. My suggested approach would be requesting the PDF with axios.get, since this automatically handles the authentication. However, I could not find out how to handle the obtained PDF in case of temporarily storing and displaying it with react.

Currently my function is able to obtain the PDF and display it in a new window but I want to include it as an element within the current page.

const getPDF = () => {
axios
  .get(
    `${process.env.REACT_APP_API}/Link/to/the/PDF/`,
    {
      responseType: "blob",
    }
  )
  .then((r) => {
    window.open(URL.createObjectURL(r.data));
  });

};

CodePudding user response:

@react-pdf/renderer is used to render pdf from your page/application and is not made to render already made pdfs

You can use react-pdf to do what you want. It works great and lets you style your component the way you want.

CodePudding user response:

In the content of the page I put the following:

<iframe src="" width={600} height={600} />

And I adapted the function to fill the iframe:

const getPDF = () => {
console.log("getPDF");
axios
  .get(`${process.env.REACT_APP_API}/Link/to/the/PDF/`, {
    responseType: "blob",
  })
  .then((r) => {
    console.log(r.data);
    const file = window.URL.createObjectURL(r.data
    );
    const iframe = document.querySelector("iframe");
    if (iframe?.src) iframe.src = file;
  })
  .catch((err: AxiosError) => {
    console.log(err);
  });

};

CodePudding user response:

So you have half the work done! in the other half, maybe an option is to look at this component:

@react-pdf/renderer

I used this package without any complaints.

  • Related