0
    await page.goto('https://www.website.com/Dashboard.aspx');

// Dynamically adding IDs to get to required page

    await page.type('#searchBox_ID' ,ids.RequestID); 
    await page.click('#buttonCLick');
    await page.waitForNavigation();

// Now page has loaded

    await page.waitForSelector('#PdfFile_Selector');
    await page.click('#PdfFile_Selector');

// this will open the file in a new window and have to click on the download button on it // how else can I do it ?

1 Answers1

0

According to the link i posted in the comment, i adapted this example on how to download a pdf. Please refer to this post for a more detailed explanation.


async function downloadPdf(page, url, targetFile, timeout_ms) {
    return new Promise(async (res, rej) => {

        // setup a timeout in case something goes wrong:
        const timeout = setTimeout(() => {
            rej(new Error('Timeout after' + timeout_ms))
        }, timeout_ms)

        // the download listener:
        const listener = req => {

            console.log('on request!. url:', req.url())

            if (req.url() === url) {
                const file = fs.createWriteStream(targetFile);

                // clear timeout and listener
                page.removeListener('request', listener)
                clearTimeout(timeout)

                //@todo
                // add proper error handling here..
                http.get(req.url(), response => {

                    response.pipe(file).on('finish', () => {
                        res()
                    })
                });
            }

        }

        page.on('request', listener)

        // open the given url!.
        // either timeout or request listener will kick in.
        page.goto(url);

    })
}

And you could call it like this:



    // ...
    const page = await browser.newPage();

    const url = 'http://www.africau.edu/images/default/sample.pdf'
    const destFile = 'file.pdf'

    console.log('lets download', url)
    await downloadPdf(page, url, destFile, 20 * 1000)

    console.log('FIle should be downloaded under', destFile)

So when your pdf page has opened, copy it's url and open it in anther tab again using downloadPDF function. Then close all tabs and you are done! .

Silvan Bregy
  • 2,544
  • 1
  • 8
  • 21
  • Thanks for the answer, didn't work for me though, So went around and used a different approach and got my task done. that procedure is not related to the question above so, not gonna comment it here. Thanks a bunch though. – Muhammad Asad Chohan Dec 16 '21 at 15:40