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.