I’m looking for assistance with creating PDFs from web pages using Puppeteer. My application is a single-page application that loads dynamic content like charts and graphs, which appear only after certain calculations.
The key issue I am facing is that I want to generate the PDF only after the entire page has completely loaded and rendered. Using fixed delays is not a reliable solution in this context.
Here’s the code I have at the moment:
const chromeBrowser = await puppeteer.launch({
executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
ignoreHTTPSErrors: true,
headless: true,
devtools: false,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const webPage = await chromeBrowser.newPage();
await webPage.goto(targetUrl, {
waitUntil: 'networkidle2'
});
await webPage.type('#user_name', 'john');
await webPage.type('#user_password', 'secret');
await webPage.click('#submit_btn');
await webPage.waitFor(2000); // I would like to avoid this line
await webPage.pdf({
path: pdfFileName,
displayHeaderFooter: true,
headerTemplate: '',
footerTemplate: '',
printBackground: true,
format: 'A4'
});
The challenge is that waitForSelector isn’t applicable because the charts and graphs don’t have specific selectors. They become visible only after the data processing is complete.
What’s the best way to ensure all content, including dynamic elements, has fully loaded?