React: download a pdf file onClick with props and react-pdf?

Viewed 698

I want to generate a pdf based in props from the UI and download it.
The props data will be fetched from an API after button click
Having a document like this.


const MyDoc = ({ text = "default" }) => {
  return (
    <Document>
      <Page>
        <Text>dsdsds{text}</Text>
      </Page>
    </Document>
  );
};

  • Using PDFViewer,can update or refresh the viewer?

const [text, setText] = useState("state");

  function change(){
    setText("updateText")
  }

  return (
    <>
      <PDFViewer width="100%" height="850px">
        <MyDoc text={{text}}/>
      </PDFViewer>
      <button onClick={change}>change props</button>
    </>
  );
};

  • Using BlobProvider,can update or refresh the URL?

const [text, setText] = useState("state");

  function change(){
    setText("updateText")
  }

  return (
    <>
      <BlobProvider
       document={<MyDoc text={{text}}/>} >
              {({ url }) => (
                <a
                  href={url}
                  target="_blank"
                  rel="noreferrer noopener"
                >
                  <b>Go to PDF</b>
                </a>
              )}
       </BlobProvider>
       <button onClick={change}>change props</button>
    </>
  );
};

  • I don't think it will be possible using PDFDownloadLink, but neither with pdf method or usePDF hook
const blob = pdf(MyDoc).toBlob();
//how can I add props to MyDoc

const [instance, updateInstance] = usePDF({ document: MyDoc });
//how can I add props to MyDoc

  function change(){
    updateInstance({ document: MyDoc });
  }


  if (instance.loading) return <div>Loading ...</div>;

  if (instance.error) return <div>Something went wrong: {error}</div>;

  return (
    <>
     <a href={instance.url} download="test.pdf">
      Download
     </a>
     <button onClick={change}>change props</button>
    </>
  );

Or is there any other simpler way with react-pdf or am I using react wrong, thank you very much

0 Answers
Related