0

So with puppeteer I'm generating the pdf in my server and it works just fine, but I also want to add another function that after I generate the PDF i send the file back to the user and the download starts via API.

So here is my function:

function createPdf async (req, res) => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('http://localhost:3000', {
      timeout: 10000,
      waitUntil: ['load', 'domcontentloaded', 'networkidle0', 'networkidle2'],
    });
    await page.pdf({
      path: `./invoices/${Math.random()}.pdf`,
      landscape: false,
      format: 'A4',
      margin: {
        top: '0px',
        right: '0px',
        bottom: '0px',
        left: '0px',
      },
    });
    await browser.close();
    if (page)
      res.status(200).send({
        success: true,
      });
  },

How can I do that?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
cutrimafyi
  • 67
  • 6
  • Does this answer your question? [Download a file from NodeJS Server using Express](https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express) – ggorlen Mar 31 '22 at 14:45

1 Answers1

1

In your server expose this end point

app.post(“/downloadPdfHere”, async (req, res, next) => {
  res.contentType("application/pdf");
  try {
    const pdf = await yourGenerator()
    res.send(pdf);  //This will generate a array buffer stream
  } catch (error) {
    console.error(error);
  }
});

In your UI try using the following to initiate your download

downloadFile = async (url, headers, body ) => {
  const response = await axios.request({
    method: 'post',
    url,
    data: body,
    headers,
    responseType: 'arraybuffer'
  });
  const downloadurl = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = downloadurl;
  // TODO for naming the response can have wins in headers
  link.setAttribute('download', 'file.pdf'); //or any other extension
  document.body.appendChild(link);
  link.click();
  };


this.downloadFile( '/downloadPdfHere', headers, body).then(()=>{
  //do anything
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Revanth
  • 21
  • 2