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

Next.js中使用@react-pdf/renderer的PDFDownloadLink报错求助

解决Next.js中@react-pdf/renderer的PDFDownloadLink服务端错误

错误原因

这个报错的核心是Next.js的服务端渲染(SSR)机制导致的:PDFDownloadLink是@react-pdf/renderer专为浏览器环境设计的API,无法在Node.js的服务端渲染流程中运行。而Next.js默认会对页面组件执行服务端渲染,组件初始化时就会在服务端触发该API调用,进而触发错误。

解决方案

根据你使用的Next.js路由模式(Pages Router / App Router),选择对应的解决方式:

方式1:Pages Router 动态导入禁用SSR

使用next/dynamic动态导入PDFDownloadLink,并指定ssr: false,强制该组件仅在浏览器端渲染:

import React from 'react';
import dynamic from 'next/dynamic';
import { Text, Document, Page } from '@react-pdf/renderer';

// 动态导入PDFDownloadLink,禁用服务端渲染
const PDFDownloadLink = dynamic(
  () => import('@react-pdf/renderer').then(mod => mod.PDFDownloadLink),
  { ssr: false }
);

const TestComponent = () => {
  return (
    <Document>
      <Page>
        <Text>Hello World</Text>
      </Page>
    </Document>
  );
};

export default function ReportGenerator() {
  return (
    <>
      <div>
        <PDFDownloadLink document={<TestComponent />} fileName="report.pdf">
          Download PDF
        </PDFDownloadLink>
        <TestComponent />
      </div>
    </>
  );
}

方式2:App Router 标记为客户端组件

如果使用Next.js 13+的App Router,在组件最顶部添加'use client'指令,强制整个组件在客户端渲染:

'use client'; // 必须放在文件最顶部
import React from 'react';
import { PDFDownloadLink, Text, Document, Page } from '@react-pdf/renderer';

const TestComponent = () => {
  return (
    <Document>
      <Page>
        <Text>Hello World</Text>
      </Page>
    </Document>
  );
};

export default function ReportGenerator() {
  return (
    <>
      <div>
        <PDFDownloadLink document={<TestComponent />} fileName="report.pdf">
          Download PDF
        </PDFDownloadLink>
        <TestComponent />
      </div>
    </>
  );
}

额外提示

  • Document/Page/Text这类PDF渲染组件可以在服务端正常运行,只有下载相关的PDFDownloadLink需要限制在客户端环境。
  • 建议保持@react-pdf/renderer为最新版本,避免版本兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:54:57