Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a pdf that opens in a new tab in puppeteer?

I have a page with a button. When I click that button, it opens a PDF in a new tab.

How can I download the PDF as a file with puppeteer?

Maybe I can write a file with the buffer from the new tab. But I am not sure how.

like image 337
GVB Avatar asked Jun 11 '18 19:06

GVB


People also ask

How does puppeteer PDF work?

Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium. It's basically a browser which you can run from Node. js. If you read the docs, the first thing it says about Puppeteer is that you can use it to Generate screenshots and PDFs of pages'.


1 Answers

A simple solution is to use the fetch api to execute the GET request. This way you can read the response, pass it to your backend and save it to disk.

Use this sample code as reference:

import fs from 'fs';

async function downloadImage(page: any, url: string, fullpath: string) {
  const data = await page.evaluate(
    // tslint:disable-next-line no-shadowed-variable
    async ({ url }) => {
      function readAsBinaryStringAsync(blob) {
        return new Promise((resolve, reject) => {
          const fr = new FileReader();
          fr.readAsBinaryString(blob);
          fr.onload = () => {
            resolve(fr.result);
          };
        });
      }

      const r = await fetch(url, {
        credentials: 'include',
        headers: {
          accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, */*;q=0.8',
          'cache-control': 'no-cache',
          pragma: 'no-cache',
          'sec-fetch-mode': 'navigate',
          'sec-fetch-site': 'same-site',
          'upgrade-insecure-requests': '1'
        },
        referrerPolicy: 'no-referrer-when-downgrade',
        body: null,
        method: 'GET',
        mode: 'cors'
      });

      return await readAsBinaryStringAsync(await r.blob());
    },
    { url }
  );

  fs.writeFileSync(fullpath, data, { encoding: 'binary' });
}

like image 78
Khalid Salomão Avatar answered Nov 04 '22 16:11

Khalid Salomão