Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js speed up puppeteer html to pdf

I have a node js application that creates dynamic content which I want users to download.

static async downloadPDF(res, html, filename) {
    const puppeteer = require('puppeteer');
    
    const browser = await puppeteer.launch({
        headless: true
    });
    
    const page = await browser.newPage()
    
    await page.setContent(html, {
        waitUntil: 'domcontentloaded'
    })
    
    const pdfBuffer = await page.pdf({
        format: 'A4'
    });
    
    res.set("Content-Disposition", "attachment;filename=" + filename + ".pdf");
    res.setHeader("Content-Type", "application/pdf");
    res.send(pdfBuffer);
    
    await browser.close()
}

Is there a way to speed up the whole process since it takes about 10 seconds to create a pdf file of size about 100kb? I read somewhere that I can launch the headless browser once then I will only be creating a new page instead of launching a browser every time I request for the file. I cannot find out a correct way of doing it.

like image 736
Albert Alberto Avatar asked Oct 21 '25 13:10

Albert Alberto


1 Answers

You could move page creation to a util and hoist it to re-use it.

const puppeteer = require('puppeteer');

let page;

const getPage = async () => {
  if (page) return page;

  const browser = await puppeteer.launch({
    headless: true,
  });

  page = await browser.newPage();

  return page;
};

.

const getPage = require('./getPage');

static async downloadPDF(res, html, filename) {
    const page = await getPage()
}
like image 51
rockingskier Avatar answered Oct 23 '25 03:10

rockingskier