Home > Mobile >  Converting the Buffer to PDF in Front End
Converting the Buffer to PDF in Front End

Time:04-01

So I'm trying to generate a pdf from the back end to the front and download it but it doens't works, rather it generates a .txt files and in some cases it generates the pdf file, its to weird.

So this is how I handle it in front with Redux:

axios
          .get(`${api}/orders/download/${res.payload.filename}`, {
            responseType: 'blob',
            'Content-Type': 'application/pdf',
          })
          .then((res) => {
            downloadFile(res);
          })
          .catch((err) => console.log(err));

        const downloadFile = async (res) => {
          // const url = window.URL.createObjectURL(new Blob([res.data]), {
          //   type: res.data.type,
          // });
          // const link = document.createElement('a');
          // link.href = url;
          // link.setAttribute('download', `${filename}.pdf`);
          // document.body.appendChild(link);
          // link.click();
          const url = window.URL.createObjectURL(await res.blob());
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', `${filename}.pdf`);
          document.body.appendChild(link);
          link.click();
        };

And this is how I generate the file:

downloadInvoice: (req, res) => {
    res.download(
      `/Users/bfzli/Code/streetcar/api/invoices/${req.params.filename}.pdf`
    );
  },

CodePudding user response:

on the frontend use:

edit:

for fetch:

const url = window.URL.createObjectURL(await response.blob());

for axios:

const url = window.URL.createObjectURL(new Blob([res.data]);

on the server use res.download:

downloadInvoice: (req, res) => {
    res.download(`/Users/bfzli/Code/streetcar/api/invoices/${req.params.filename}.pdf`, (err) => {
        fs.unlinkSync(`/Users/bfzli/Code/streetcar/api/invoices/${req.params.filename}.pdf`)
    });
}
  • Related