Puppeteer PDF generation race condition with front-end event dispatch

I’m working on a web application that generates PDFs using Puppeteer on the back-end, based on content rendered by a front-end Lightning Web Component (LWC). I’m encountering a timing issue where Puppeteer might be trying to generate the PDF before the front-end has finished rendering.

Back-end code (Node.js with Puppeteer):

async function generatePdf(url, footerInfo) {

    const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
    const webPage = await browser.newPage();
    webPage.on('console', msg => {
        console.log(msg.text());
        for (let i = 0; i < msg.stackTrace().length; ++i) {
            console.log(
                `  Line: ${msg.stackTrace()[i].lineNumber} Column: ${msg.stackTrace()[i].columnNumber} File: ${msg.stackTrace()[i].url}`);
        }
    });
    webPage.on('pageerror', ({message}) => console.log(message));

    await webPage.goto(url, {waitUntil: 'networkidle0'});

    //await webPage.waitForTimeout(10000);
    
    // custom event
    await webPage.evaluate(() => {
        return new Promise((resolve) => {
            console.log('dispatching pdfrendered event');
            window.addEventListener('pdfrendered', resolve, { once: true });
            // a timeout is addedd in case the event is never fired
            setTimeout(resolve, 30000);
        });
    });

    const footerHtml = footerHelper.generateFooterHtml(footerInfo);
    const pdfFileStream = await webPage.createPDFStream({
        printBackground: true,
        format: 'A3',
        margin: {
            top: '48px',
            bottom: '84px',
            left: '48px',
            right: '48px',
        },
        displayHeaderFooter: true,
        headerTemplate: '<div/>',
        footerTemplate: footerHtml
    });

    return {
        browser: browser,
        pdfFileStream: pdfFileStream,
    };
}

Front-end code (LWC):

import { api, LightningElement } from 'lwc';

export default class PeRelatedListItem extends LightningElement {
  @api relatedList;
  @api headerBackgroundColor;
  @api textColor;
  @api showBorder;
  pdfRendered = false;

  get headerStyle() {
    const backgroundColor = this.headerBackgroundColor || this.relatedList.subsectionBackgroundColor;
    const textColor = this.textColor || this.relatedList.subsectionTextColor;
    return backgroundColor || textColor ?
        `background-color: ${backgroundColor} !important;` : '';
  }

  get cellStyle() {
    return this.textColor ? `color: ${this.textColor} !important;` : '';
  }

  get hasRelatedRecords() {
    return this.relatedList.relatedRecords && this.relatedList.relatedRecords.length > 0;
  }

  get tableClass() {
    return this.showBorder
        ? 'slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered'
        : 'slds-table slds-table_cell-buffer slds-table_bordered';
  }

  renderedCallback() {
    if (this.headerStyle) {
      const headerCells = this.template.querySelectorAll('th');
      headerCells.forEach(cell => {
        cell.style.cssText = this.headerStyle;
      });
    }
    if (this.cellStyle) {
      const dataCells = this.template.querySelectorAll('td');
      dataCells.forEach(cell => {
        cell.style.cssText = this.cellStyle;
      });
    }

    if (this.isPdfRelatedList && !this.pdfRendered) {
      console.log('PDF related list detected');
      if (window['pdfjs-dist/build/pdf']) {
        this.renderPdf();
      } else {
        this.addEventListener('pdfjsloaded', this.renderPdf);
      }
      this.pdfRendered = true;
    }
    else {
      console.log('PDF related list NOT detected');
      this.dispatchEvent(new CustomEvent('pdfrendered', { bubbles: true, composed: true }));
    }
  }

  get isPdfRelatedList() {
    return this.relatedList?.type === 'pdfRelatedList' &&
        this.relatedList?.relatedRecords?.some(record => record.pdfDataUrl);
  }

  async renderPdf() {

    const pdfContainer = this.template.querySelector('.pdf-container');
    //pdfContainer.innerHTML = '';

    for (const record of this.relatedList.relatedRecords) {
      const pdfData = record.pdfDataUrl;
      if (!pdfData) {
        console.error('PDF data not loaded for record:', record.id);
        continue;
      }

      const pdfjsLib = window['pdfjs-dist/build/pdf'];
      let pdfDoc;
      try {
        if (pdfData instanceof Blob) {
          pdfDoc = await pdfjsLib.getDocument({data: await pdfData.arrayBuffer()}).promise;
        } else if (pdfData instanceof ArrayBuffer || pdfData instanceof Uint8Array) {
          pdfDoc = await pdfjsLib.getDocument({data: pdfData}).promise;
        } else {
          console.error('Unsupported PDF data type');
          continue;
        }

        const numPages = pdfDoc.numPages;

        for (let pageNum = 1; pageNum <= numPages; pageNum++) {
          const page = await pdfDoc.getPage(pageNum);
          const scale = 1;
          const viewport = page.getViewport({scale: scale});

          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          const renderContext = {
            canvasContext: context,
            viewport: viewport
          };

          await page.render(renderContext).promise;
          pdfContainer.appendChild(canvas);

          // Add some space between pages
          if (pageNum < numPages) {
            const spacer = document.createElement('div');
            spacer.style.height = '20px';
            pdfContainer.appendChild(spacer);
          }
        }

        // Add a larger spacer between different PDFs
        const pdfSpacer = document.createElement('div');
        pdfSpacer.style.height = '40px';
        pdfContainer.appendChild(pdfSpacer);

      } catch (error) {
        console.error('Error rendering PDF:', error);
        const errorMessage = document.createElement('p');
        errorMessage.textContent = `Error rendering PDF: ${error.message}`;
        pdfContainer.appendChild(errorMessage);
      }
    }

    // Emit custom event indicating all PDFs have been rendered
    this.dispatchEvent(new CustomEvent('pdfrendered', { bubbles: true, composed: true }));
  }
}

The issue:
When this.isPdfRelatedList is false, the front-end immediately dispatches the ‘pdfrendered’ event. However, this event might be dispatched before Puppeteer has a chance to set up the event listener in webPage.evaluate().
Questions:

How can I ensure that Puppeteer doesn’t miss the ‘pdfrendered’ event when it’s dispatched immediately?
Is there a better way to synchronize the front-end rendering completion with the back-end PDF generation process?
Should I use a different approach altogether for non-PDF content?

Any insights or best practices for handling this kind of front-end/back-end synchronization with Puppeteer would be greatly appreciated.

I initially expected the ‘pdfrendered’ event to be captured by Puppeteer regardless of when it was dispatched. However, I found that when this.isPdfRelatedList is false, the event seems to be missed entirely.
I tried increasing the timeout in the Puppeteer evaluate function from 30 seconds to 60 seconds, thinking it might give more time for the event to be dispatched and captured. This didn’t solve the issue and only resulted in longer wait times for non-PDF content.

New contributor

user18913859 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật