【问题标题】:Rendering a page after generating PDF with puppeteer?使用 puppeteer 生成 PDF 后渲染页面?
【发布时间】:2023-03-28 10:20:01
【问题描述】:

我目前正在尝试使用 puppeteer 生成 PDF,然后向用户呈现带有“谢谢”消息的页面。一旦用户点击该页面,Puppeteer PDF 将有望开始下载到用户的机器上。但我遇到了一些麻烦。

从表单收集一些基本信息后,我可以成功地将用户重定向到我希望他们访问的页面:

app.post("/generatepdf", function (req, res) {

  UserPdfRequest.create({ email: req.body.email, companyName: req.body.companyName }, function (err, createdRequest) {
    if (err) {
      console.log(err);
    } else {
      console.log(createdRequest);
      res.redirect("/" + createdRequest._id + "/pdf-download");
    }
  })

});

然后,我将它们发送到我的路线,该路线负责查找相关用户、生成 PDF,然后呈现感谢页面:

app.get("/:companyId/pdf-download", function (req, res) {

  UserPdfRequest.findById(req.params.companyId, function (err, foundRequest) {
    if (err) {
      console.log(err);
    } else {
      console.log(foundRequest);

      (async () => {
        const browser = await puppeteer.launch()
        const page = await browser.newPage()
        const url = 'http://localhost:3000/' + req.params.companyId + '/pdf-download';
        await page.goto(url, {waitUntil: 'networkidle0'});
        const buffer = await page.pdf({ format: "A4", printBackground: true });
        res.type('application/pdf')
        res.send(buffer)
        browser.close()
      })()

      res.render("pdfDownload", { email: foundRequest.email, companyName: foundRequest.companyName });
    }
  })

});

但是当我进入感谢页面时,我的 PDF 并没有开始下载。此外,我的 console.log(foundRequest) 似乎在我的终端中一遍又一遍地快速登录,并且我还收到以下错误:

https://imgur.com/ZsApRHn

鉴于我对异步没有太多经验,我知道我可能在这里不知所措。我确定这是我缺少的一个简单修复;但是,任何帮助(和解释)都将非常有价值和感激。感谢您的时间!

【问题讨论】:

    标签: javascript pdf pdf-generation puppeteer


    【解决方案1】:

    您正在同一个响应对象上调用sendrender。您可以发送数据或发送 html,但不能针对同一请求执行此操作。 通常可以通过打开一个新标签进行下载来解决。

    【讨论】:

    • 感谢您的评论。您认为为 PDF 生成添加另一个路由,然后在页面加载后使用 AJAX 调用在 Javascript 中调用该路由会更好吗?或将其连接到按钮。这就是我目前的想法,但我希望有更多的想法。
    • 发送 AJAX 意味着你需要在客户端处理它——你需要实现类似here 描述的东西。只需在表单中添加target="_blank" 即可打开一个新选项卡,但仍需要一些代码来实现您的第二个要求——在表单提交后更改页面。
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2013-07-31
    • 2023-01-04
    相关资源
    最近更新 更多