What is the method to download PDFs using Puppeteer?

Need help downloading PDFs via Puppeteer. Below is my experimental code:

const capturePage = new Promise(cb => {
  browser.once('targetcreated', target => cb(target.page()));
});
await mainPage.click('#btnFetchPDF');
await mainPage.waitForTimeout(2000);
const pdfWindow = await capturePage;
await pdfWindow._client.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: '/tmp/docs' });

I encountered similar problems when working with PDF downloads via Puppeteer. In my experience, generating PDFs directly using Puppeteer’s page.pdf method offers a more reliable approach than trying to intercept a download triggered by a click. By rendering the page content and converting it into a PDF programmatically, potential timing and behavioral issues are mitigated. This technique was particularly useful for handling pages that don’t naturally lend themselves to straightforward download processes, allowing for better control over format and content in the resulting PDF.

i’ve had luck using response intercept. by listening to page.on(‘response’), you can grab the pdf data and write it with fs. saves you from pesky popup issues and gives more control over the actual file downloaded

I have found that another effective approach is to capture the network request for the PDF after the button click, rather than trying to intercept a new window. In my setup I enable request interception and wait for the request that has the content type for PDF. Once the request is captured, I can use response.buffer() to get the PDF file data and write it to disk. This approach allows for better error handling and dealing with scenarios where the device may take longer to render the file, ensuring a more resilient download process overall.

My approach has been to avoid new target creation and instead retain control within the original page session. I configure the download behavior in the main page context by enabling it before simulating the PDF generation click. This means I set up the download path via Page.setDownloadBehavior on the main page rather than waiting for a new window or tab. With this method I can monitor the download folder for the arrival of the file, which has worked quite reliably in my automated tests, providing a streamlined process.