React-pdf send pdf to server without download pdf.
Tags: react, reactpdf, sendpdftoserver, javascript
Published: 2023-10-17 06:56:06

So we all are know that why we use react-pdf. If no im explaing basics.
Basically react-pdf is used for make pdf from front-end. Like you making a website that need to download the pdf. React-pdf is handling that so much easy way. They have Prefined component which we can use and design the pdf. If you need More details explanation please [go here](https://react-pdf.org/).

**So how react-pdf package acctually work?**
In React-PDF, when you generate a PDF document, it's typically stored as a Blob (Binary Large Object) in memory. You can then use this Blob to display the PDF in your application or save it to the user's device.

**So now the question is why i can't send the file directly?**
Beacause the file is not store anywhere in your device if you don't download. And the process is not good like first you need to download and then send it to the server.The invoice pdf that you designed if you need to send that one email. That means you need to connect the email server and need to send the file. So it's not easy to upload or post file directly.

So the solution is,

if you go through the [react-pdf](https://react-pdf.org/advanced) document you can see 

they have a hook call usePDF()
and its by default receive the document that you have designed.
For example I designed the document:

`const MyDoc = (
  <Document>
    <Page>
      // My document data
    </Page>
  </Document>
);`
Now i can call that with usePDF like
`  const [instance, updateInstance] = usePDF({ document: MyDoc });`
So here the instace give us an object. and there we have the blob url. Now we need to convert this blob url to bas64 data. For that we can easily send it to the server.

The Full Code example is:
`import { usePDF, Document, Page } from '@react-pdf/renderer';
const MyDoc = (
  <Document>
    <Page>
      // My document data
    </Page>
  </Document>
);`
`const App = () => {
  const [pdfBase64, setPdfBase64] = useState()
  const [instance, updateInstance] = usePDF({ document: MyDoc });`

 `// get pdf file invoice
  function blobToBase64(blobURL) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'blob';
      xhr.onload = () => {`
        `const reader = new FileReader();
        reader.onloadend = () => {
          if (reader.result) {
            resolve(reader.result.split(',')[1]);
          } else {
            reject("Error reading the blob.");
          }
        };
        reader.readAsDataURL(xhr.response);
      };`
      `xhr.onerror = reject;
      xhr.open('GET', blobURL);
      xhr.send();
    });
  }`

`// Usage
  const blobURL = instance?.url;`

  `useEffect(() => {
    if (blobURL) {
      blobToBase64(blobURL)
        .then(base64String => {
          setPdfBase64(base64String);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }, [blobURL])`
`function onSubmit(data) {
         axios.post(${server_url_here},pdfBase64)        
.then(res => {
          console.log(res);
        })
  }
  return (
     <button onClick={onSubmit}>
                Cancel
              </button>
  );
}`

So if you open your network tab and see the result. You send the pdf data with base64.

Thanks for getting into touch.