如何下载在木偶玩家的新标签中打开的pdf文件? [英] How to download a pdf that opens in a new tab in puppeteer?

查看:36
本文介绍了如何下载在木偶玩家的新标签中打开的pdf文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮的页面。当我单击该按钮时,它会在新选项卡中打开PDF。

如何使用Pupeteer将PDF下载为文件?

也许我可以使用新选项卡中的缓冲区编写文件。但我不确定是怎么做到的。

推荐答案

简单的解决方案是使用fetch接口执行GET请求。这样,您可以读取响应,将其传递到后端并将其保存到磁盘。

使用此示例代码作为参考:

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' });
}

这篇关于如何下载在木偶玩家的新标签中打开的pdf文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆