如何使用 Puppeteer 将 React App 组件打印为 PDF

问题描述 投票:0回答:1

我必须在我的 React 应用程序中实现以下场景:

  1. 一些未经授权的用户访问了名为“请求计划报告”的页面
  2. 他们发送请求
  3. 管理员批准请求
  4. 用户收到附有 PDF 文件的电子邮件(包含报告)。

我的做法是:

  1. React App 向服务器发送请求
  2. 如果管理员批准请求,服务器将处理
  3. 服务器将通过简单的 Axios GET 请求调用 Puppeteer 容器上启动的端点。
  4. Puppeteer 将打开新的无头浏览器窗口,其中包含收到的 React App url
  5. PDF 缓冲区返回到服务器并由nodemailer 发送。

当我通过时,一切正常,例如https://google.com。 PDF 已正确生成。但 React App url 返回空 PDF。我不知道有什么问题:(

NestJS 服务器代码:

await axios
  .get(`${PUPPETEER_APP_URL}/pdf`, {
    responseType: 'arraybuffer',
    params: { url: programUrl }
  })

Puppeteer 应用程序代码:

路由器:

app.get('/pdf', async (req, res) => {
  const url = req.query.url
  const result = await generatePdf(`${CLOUD_APP_URL}/${url}`)
  res.contentType('application/pdf');
  res.send(result);
});

服务:

const puppeteer = require('puppeteer');

const generatePdf = async (payload) => {
  try {
    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
  
    const page = await browser.newPage();
    await page.goto(payload, {
      waitUntil: ['domcontentloaded', 'networkidle0', 'load']
    })
    await page.emulateMediaType('screen')
    const pdf = await page.pdf();
    await browser.close();
  
    return pdf;
  } catch (error) {
    console.log('GENERATE PDF ERROR :>> ', error);
  }
};

module.exports = generatePdf;

响应数据看起来像

data: <Buffer >

node.js reactjs puppeteer pdf-generation
1个回答
0
投票

希望有帮助🙏🏻

 const downloadAsPDF = async ({ documentId }) => {
        let pdf = await fetch(url,{
            endpoint: `services/pdf?documentId=${documentId}`,
            method: 'GET',
            headers: {
                'Content-Type': 'application/pdf'
            }
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(pdf);
        link.download = `your-file-name.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
© www.soinside.com 2019 - 2024. All rights reserved.