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

PDFKit生成的PDF如何在React项目的浏览器新标签页中打开?

解决方案

核心问题

当前后端返回的Content-Disposition响应头值为attachment,该标识会强制浏览器触发下载行为,而非在标签页内预览。

第一步:修改后端响应头

修改api.js中响应头配置,将attachment替换为inline即可让浏览器默认执行预览逻辑:

static async generatePDF(req, res) {
  const doc = new PDFDocument({bufferPages: true});

  let buffers = [];
  doc.on('data', buffers.push.bind(buffers));
  doc.on('end', () => {
      let pdfData = Buffer.concat(buffers);
      res.writeHead(200, {
      'Content-Length': Buffer.byteLength(pdfData),
      'Content-Type': 'application/pdf',
      // 把attachment改成inline即可
      'Content-disposition': 'inline;filename=test.pdf',
      // 可选添加,避免浏览器嗅探内容类型导致行为异常
      'X-Content-Type-Options': 'nosniff'
      })
      .end(pdfData);
  
  });
  
  doc.font('Times-Roman')
       .fontSize(22)
       .text("TEST PDF FILE");
  doc.end();
}

第二步:前端调用适配

根据你的鉴权方式选择对应调用方案:

  • 场景1:接口鉴权依赖Cookie(同域项目)
    直接通过以下代码调用即可,无需额外处理:
    window.open('/generate-pdf', '_blank')
    
  • 场景2:接口鉴权需要自定义请求头(比如JWT放在Authorization头中)
    先请求拿到PDF的Blob数据,再生成临时URL打开新标签:
    // React前端调用示例
    const openPDF = async () => {
      const res = await fetch('/generate-pdf', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${你的用户token}`
        }
      })
      const pdfBlob = await res.blob()
      const pdfUrl = URL.createObjectURL(pdfBlob)
      // 用a标签触发打开,避免部分浏览器拦截window.open弹窗
      const a = document.createElement('a')
      a.href = pdfUrl
      a.target = '_blank'
      a.click()
      // 10秒后释放临时URL占用的内存
      setTimeout(() => URL.revokeObjectURL(pdfUrl), 10000)
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:24:03