在React JS中如何在单击按钮时调用puppeteer脚本?

时间:2019-12-12 08:51:22

标签: javascript reactjs puppeteer buttonclick

我想在React JS中使用puppeteer下载pdf,单击按钮。

我创建了一个单独的js文件,并在package.json中进行了更改以运行该文件。

generate-pdf.js

const puppeteer = require('puppeteer');

    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      console.log("page",page)
      await page.goto('http://localhost:3000/');
      //await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: './myAwesomeDownloadFolder'});
      await page.emulateMedia('screen');
      await page.pdf({
        path: './react.pdf', // path (relative to CWD) to save the PDF to.
        printBackground: true,// print background colors
        width: '612px', // match the css width and height we set for our PDF
        height: '792px',
      });
      //await browser.close();
    })()

package.json(脚本)

"scripts": {
    "generate": "npx babel-node scripts/generate-pdf.js",
    "start": "react-scripts start",
    "dev": "concurrently \"npm run start\" \"npm run generate\"",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

当我在本地运行“ npm run dev”时,两个执行同时发生。该应用程序随pdf生成一起开始。

但是我的用例是从UI上单击按钮时生成pdf。单击按钮时会显示以下错误消息。

enter image description here

我尝试使用'child_proces',但不能在同一环境中运行。还有其他方法可以实现相同目的。

0 个答案:

没有答案