Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Puppeteer optimalization

I have a web app that generates quite large PDF documents, possibly 100 pages and more.

The workflow is this:

  1. Generate html using nunjucks templates
  2. Open a puppeteer browser
  3. Create PDF front page (see code below)
  4. Create PDF pages
  5. Merge the pages to a document and create a buffer
import { PDFDocument } from 'pdf-lib';

const pdfHtml = await nunjucks.render(...);

const theBrowser = await puppeteer.launch({
  args: [
    '--disable-dev-shm-usage',
    '--no-first-run',
    '--no-sandbox',
    '--no-zygote',
    '--single-process',
  ],
  headless: true
});

const page = await theBrowser.newPage();

awaut page.setContent(`${pdfHtml}`, { waitUntil: 'networkidle0' });

const frontPage: Buffer = await page.pdf({
  ... someOptions,
  pageRanges: '1'
});

const pdfPages: Buffer = await page.pdf({
  ... someOptions,
  pageRanges: '2-',
  footerTemplate: ...,
});

const pdfDoc = await PDFDocument.create();
const coverDoc = await PDFDocument.load(frontPage);
const [coverPage] = await pdfDoc.copyPages(coverDoc, [0]);
pdfDoc.addPage(coverPage);

const mainDoc = await PDFDocument.load(reportPages);
for (let i = 0; i < mainDoc.getPageCount(); i++) {
    const [aMainPage] = await pdfDoc.copyPages(mainDoc, [i]);
    pdfDoc.addPage(aMainPage);
}

pdfBytes = Buffer.from(await pdfDoc.save());
// handle the bytes here

When the PDF gets really big, this operation will take quite a while and use lots of memory doing so, stalling the API until its completion. What can I do to optimalize this? Or are there other tools I can use to avoid stalling the API?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!