用途
react-pdf 是 json-render 项目中的 React PDF 渲染器,包名为 @json-render/react-pdf。它用于从 JSON 规格(Spec)生成 PDF 文档,底层使用 @react-pdf/renderer。当需要以声明式 JSON 描述文档结构并渲染为 PDF 时,可以使用该工具。
安装
npm install @json-render/core @json-render/react-pdf
主要能力
渲染 API
提供三种渲染方式:
import { renderToBuffer, renderToStream, renderToFile } from "@json-render/react-pdf";
// 内存缓冲区
const buffer = await renderToBuffer(spec);
// 可读流(可管道到 HTTP 响应)
const stream = await renderToStream(spec);
stream.pipe(res);
// 直接写入文件
await renderToFile(spec, "./output.pdf");
所有渲染函数都接受可选的第二个参数:{ registry?, state?, handlers? }。
标准组件
| 组件 | 说明 |
|---|---|
| Document | 顶层 PDF 包装器(必须是根节点) |
| Page | 页面,支持 size(A4、LETTER)、orientation、margins |
| View | 通用容器(padding、margin、background、border) |
| Row、Column | 弹性布局,支持 gap、align、justify |
| Heading | h1-h4 标题文本 |
| Text | 正文文本(fontSize、color、weight、alignment) |
| Image | 来自 URL 或 base64 的图片 |
| Link | 带文本和 href 的超链接 |
| Table | 带类型化列和行的数据表格 |
| List | 有序或无序列表 |
| Divider | 水平分隔线 |
| Spacer | 空白垂直间距 |
| PageNumber | 当前页码和总页数 |
自定义目录
可以通过 defineCatalog 与 defineRegistry 扩展组件目录:
import { defineCatalog } from "@json-render/core";
import { schema, defineRegistry, renderToBuffer } from "@json-render/react-pdf";
import { standardComponentDefinitions } from "@json-render/react-pdf/catalog";
import { z } from "zod";
const catalog = defineCatalog(schema, {
components: {
...standardComponentDefinitions,
Badge: {
props: z.object({ label: z.string(), color: z.string().nullable() }),
slots: [],
description: "A colored badge label",
},
},
actions: {},
});
const { registry } = defineRegistry(catalog, {
components: {
Badge: ({ props }) => (
<View style={{ backgroundColor: props.color ?? "#e5e7eb", padding: 4 }}>
<Text>{props.label}</Text>
</View>
),
},
});
const buffer = await renderToBuffer(spec, { registry });
外部存储(受控模式)
传入 StateStore 可完全控制状态:
import { createStateStore } from "@json-render/react-pdf";
const store = createStateStore({ invoice: { total: 100 } });
store.set("/invoice/total", 200);
嵌套列表可以在外层 repeat 内将 repeat.statePath 设置为 { "$item": "field" }。
服务端安全导入
可以在不引入 React 的情况下导入 schema 和目录:
import { schema, standardComponentDefinitions } from "@json-render/react-pdf/server";
使用方式
先定义符合 Spec 类型的 JSON 规格,指定 root 根节点以及 elements 中各元素的 type、props 和 children,然后调用 renderToBuffer、renderToStream 或 renderToFile 进行渲染。示例中展示了包含 Document、Page、Heading、Table 的发票文档结构。
适用场景
适合需要以 JSON 声明式描述并生成 PDF 文档的场景,例如发票、报表等结构化文档的批量生成,以及需要将 PDF 输出到内存、HTTP 流或文件的各类服务端应用。
限制
资料未提供关于收费、价格、平台兼容性、性能表现或具体效果的信息,暂未提供。