You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express与Node.js生成PDF接口返回空文件问题咨询

问题原因及解决方案

核心原因

  1. 当给page.pdf()添加path参数时,Puppeteer会将PDF写入本地路径,不会返回Buffer数据,此时pdfStream为undefined,返回给客户端自然是空内容。
  2. 未配置正确的HTTP响应头,浏览器无法识别返回的二进制数据为PDF文件,导致解析失败,表现为空文件。

修复方案

  1. 移除path参数,确保page.pdf()返回PDF格式的Buffer。
  2. 设置正确的响应头,告知浏览器返回内容类型及下载行为。
  3. 推荐使用新版无头模式headless: 'new',旧版headless: true已被弃用,稳定性更差。

修改后的代码

module.exports = async (req, res, next) => {
  const chromium = require('chrome-aws-lambda')
  const puppeteer = require('puppeteer-core')
  let browser = null
  
  try {
    browser = await puppeteer.launch({
      args: chromium.args,
      executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
      headless: 'new'
    })
    const page = await browser.newPage()
    await page.setContent('<html><body><h1>Hello, PDF!</h1></body></html>')
    // 不设置path,获取PDF Buffer
    const pdfBuffer = await page.pdf({format: 'A4' })
    
    // 配置响应头,让浏览器正确识别并触发下载
    res.setHeader('Content-Type', 'application/pdf')
    res.setHeader('Content-Disposition', 'attachment; filename="output.pdf"')
    // 发送PDF Buffer
    res.end(pdfBuffer)
  } catch (error) {
    console.error(error)
    return res.status(500).send({
      status: 0,
      error: 'download failed'
    })
  } finally {
    if (browser !== null) {
      await browser.close()
    }
  }
}

额外注意

如果你的HTML包含动态渲染内容(比如异步加载的DOM),需要添加等待逻辑,确保内容完全渲染后再生成PDF,例如:

// 等待指定元素加载完成
await page.waitForSelector('h1')

内容的提问来源于stack exchange,提问作者Tareq Assi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:17:49