npx skills add https://github.com/molefrog/skills --skill react-pdf(async () => { ... })() 模式。Font.registerHyphenationCallback((word) => [word]);。references/google-fonts.txt - 包含 TrueType URL 的约 65 种流行 Google 字体的元数据。每行是一个制表符分隔的字体变体格式:字体名称、样式、类别、字重、。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
urlreferences/components.md - 完整的组件 API 参考和支持的 CSS 属性assets/example-template.tsx - 演示固定页脚、页码和不可分割内容的最小工作示例。开始前请阅读此文件以了解基本模式。注意:此处未展示所有 API — 请始终查阅文档和 references/components.md 以获取完整 API。npm install react @react-pdf/renderer
npm install -D tsx @types/react
tsx 通过 Node 直接运行 TypeScript + JSX 文件,无需配置 — 不需要 tsconfig.json。它在底层使用 esbuild 并自动处理 JSX 转换。
有关完整的组件属性和 CSS 属性,请参阅 references/components.md。
import React from "react";
import { Document, Page, Text, View, StyleSheet, renderToFile } from "@react-pdf/renderer";
const styles = StyleSheet.create({
page: { flexDirection: "column", backgroundColor: "#ffffff", padding: 40 },
title: { fontSize: 24, marginBottom: 20, fontWeight: "bold" },
text: { fontSize: 12, lineHeight: 1.5 },
});
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={{ margin: 10, padding: 20 }}>
<Text style={styles.title}>文档标题</Text>
<Text style={styles.text}>你的内容在这里</Text>
</View>
</Page>
</Document>
);
(async () => {
await renderToFile(<MyDocument />, "./output.pdf");
console.log("PDF 已保存!");
})();
PDF 生成脚本使用 JSX,Node 无法直接运行。使用 tsx 来执行它们:
npx tsx my-document.tsx
npx tsx 无需全局安装 tsx 即可工作 — 它会按需下载。如果 tsx 已作为开发依赖项安装(npm install -D tsx),则无需 npx 下载步骤即可立即运行。
始终将渲染代码包裹在异步 IIFE 中:
// 正确
(async () => {
await renderToFile(<MyDocument />, "./output.pdf");
})();
// 错误 - 顶层 await 可能失败
await renderToFile(<MyDocument />, "./output.pdf");
要直观检查生成的 PDF,请将页面转换为图像。首先尝试 pdftoppm(通常预装),如果不可用,则回退到 Python 的 PyMuPDF。
选项 1:pdftoppm (poppler-utils) — 首选,在许多环境中无需安装:
pdftoppm -png -r 200 document.pdf preview
# → preview-1.png, preview-2.png, ...
选项 2:PyMuPDF (Python) — 如果 pdftoppm 不可用,则作为备选方案:
pip install pymupdf
import fitz
doc = fitz.open("document.pdf")
for i, page in enumerate(doc):
pix = page.get_pixmap(dpi=200)
pix.save(f"page-{i+1}.png")
import { renderToFile, renderToBuffer } from "@react-pdf/renderer";
// 渲染到文件
(async () => {
await renderToFile(<MyDocument />, "./document.pdf");
})();
// 渲染到缓冲区
(async () => {
const buffer = await renderToBuffer(<MyDocument />);
})();
三种方法:StyleSheet.create()、内联对象或混合数组。
const styles = StyleSheet.create({ container: { padding: 20 } });
<View style={styles.container} />
<View style={{ padding: 20 }} />
<View style={[styles.container, { marginTop: 10 }]} />
pt(默认,72 DPI)、in、mm、cm、%、vw、vh
{
// Flexbox
flexDirection: "row", justifyContent: "space-between", alignItems: "center",
flexWrap: "wrap", gap: 10,
// 盒模型
margin: 10, padding: 20, width: "100%", height: 200,
// 边框
borderWidth: 1, borderColor: "#333", borderRadius: 5, borderStyle: "solid",
// 颜色
backgroundColor: "#f0f0f0", color: "#000", opacity: 0.8,
// 排版
fontSize: 12, fontWeight: "bold", fontFamily: "Helvetica", fontStyle: "italic",
lineHeight: 1.5, textAlign: "center", textDecoration: "underline",
textTransform: "uppercase", letterSpacing: 1,
// 定位
position: "absolute", top: 0, left: 0, right: 0, bottom: 0, zIndex: 10,
// 变换
transform: "rotate(45deg)", transformOrigin: "center",
}
本地文件最可靠。远程 URL 可能因网络/CORS 问题而失败。
import { Image } from '@react-pdf/renderer';
<Image src="./images/photo.jpg" style={{ width: 200, height: 150 }} />
<Image src={{ data: buffer, format: 'png' }} />
SVG 文件不能用作 Image 源。 读取 SVG 源并使用 react-pdf 的 Svg 组件重新创建。
import { Svg, Circle, Rect, Path, Line, G, Defs, LinearGradient, Stop } from "@react-pdf/renderer";
<Svg width="200" height="200" viewBox="0 0 200 200">
<Defs>
<LinearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#3498db" />
<Stop offset="100%" stopColor="#9b59b6" />
</LinearGradient>
</Defs>
<Circle cx="100" cy="100" r="50" fill="url(#grad1)" />
<Rect x="10" y="10" width="50" height="50" fill="#e74c3c" />
<Path d="M10,50 Q50,10 90,50" stroke="#2ecc71" strokeWidth="2" fill="none" />
</Svg>;
从图标库读取 SVG 源并转换为 react-pdf 的 Svg 组件:
npm install lucide-static
import { Svg, Path, Rect } from "@react-pdf/renderer";
// 从 lucide-static/icons/mail.svg 转换而来
const MailIcon = ({ size = 12, color = "#888" }) => (
<Svg width={size} height={size} viewBox="0 0 24 24">
<Path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7" stroke={color} strokeWidth={2} fill="none" />
<Rect x="2" y="4" width="20" height="16" rx="2" stroke={color} strokeWidth={2} fill="none" />
</Svg>
);
<Link src="https://example.com"><Text>访问网站</Text></Link>
<View id="section-1"><Text>目标</Text></View>
<Link src="#section-1"><Text>跳转到第 1 节</Text></Link>
<Text render={({ pageNumber, totalPages }) => `第 ${pageNumber} 页,共 ${totalPages} 页`} />
<Page size="A4">
<View fixed style={{ position: "absolute", top: 20, left: 30, right: 30 }}>
<Text>页眉</Text>
</View>
<View style={{ marginTop: 60, marginBottom: 60 }}>
<Text>内容</Text>
</View>
<Text
fixed
style={{ position: "absolute", bottom: 20, left: 30, right: 30, textAlign: "center" }}
render={({ pageNumber, totalPages }) => `第 ${pageNumber} 页,共 ${totalPages} 页`}
/>
</Page>
<View break /> // 强制分页
<View wrap={false}><Text>保持在一起</Text></View> // 防止内部断开
<Text orphans={2} widows={2}>长文本...</Text> // 孤行/寡行控制
<View minPresenceAhead={100}><Text>内容</Text></View> // 分页前的最小空间
关键:所有字体源必须是本地文件路径。 远程 URL 无效。
import { Font } from "@react-pdf/renderer";
Font.register({
family: "Roboto",
fonts: [
{ src: "./fonts/Roboto-Regular.ttf", fontWeight: "normal" },
{ src: "./fonts/Roboto-Bold.ttf", fontWeight: "bold" },
{ src: "./fonts/Roboto-Italic.ttf", fontStyle: "italic" },
],
});
// 使用自定义字体时,务必禁用断字
Font.registerHyphenationCallback((word) => [word]);
内置字体 : Courier、Helvetica、Times-Roman(每种都有粗体、斜体/倾斜变体)
字体字重值 : thin (100)、ultralight (200)、light (300)、normal (400)、medium (500)、semibold (600)、bold (700)、ultrabold (800)、heavy (900)
使用 references/google-fonts.txt 查找字体 URL,然后下载到本地:
# 查找字体 URL
grep "^Roboto" skills/react-pdf/references/google-fonts.txt | grep "700" | grep "normal"
# 下载
mkdir -p fonts
curl -sL "<url-from-grep>" -o fonts/Roboto-Bold.ttf
# 验证 - 必须显示 "TrueType Font data"
file fonts/Roboto-Bold.ttf
如果 file 显示 "HTML document" 或 "ASCII text",则下载失败。尝试不同的 URL 或在 GitHub 上搜索包含 TTF 文件的字体官方仓库。
表情符号不会在 PDF 中渲染,除非你注册了表情符号源。安装 twemoji-emojis 以获取本地 Twemoji PNG 资源 — 渲染时无需网络连接。
npm install twemoji-emojis
import { Font } from "@react-pdf/renderer";
Font.registerEmojiSource({
format: "png",
url: "node_modules/twemoji-emojis/vendor/72x72/",
});
然后直接在 Text 中使用表情符号:<Text>Hello 🚀🎉</Text>
// Canvas 绘图
<Canvas style={{ width: 200, height: 200 }}
paint={(painter, w, h) => { painter.circle(w/2, h/2, 50).fill("#3498db"); }} />
// 注释
<Note style={{ color: "yellow" }}>注释文本</Note>
// 断字
Font.registerHyphenationCallback((word) => [word]); // 禁用
// 调试模式 - 可视化边界
<View debug><Text debug>调试文本</Text></View>
// 文档元数据
<Document title="我的文档" author="作者" subject="报告" language="en-US" pdfVersion="1.5" />
StyleSheet.create() — 定义一次样式并重复使用cache={true}fixed 属性debug={true} 可视化元素边界文本溢出 : <Text style={{ width: 200, maxLines: 3, textOverflow: "ellipsis" }}>...</Text>
缺少字体 : 下载到本地并使用本地文件路径注册。远程 URL 无效。
意外的分页 : 使用 wrap={false} 保持内容在一起,或使用 <View break /> 强制分页。
每周安装次数
263
仓库
GitHub 星标数
134
首次出现
2026年2月12日
安全审计
安装于
opencode239
gemini-cli232
codex229
github-copilot216
amp207
kimi-cli206
(async () => { ... })() pattern.Font.registerHyphenationCallback((word) => [word]); after registering custom fonts.references/google-fonts.txt - Metadata for ~65 popular Google Fonts with TrueType URLs. Each line is a font variant in tab-separated format: font name, style, category, weight, url.references/components.md - Full component API reference and supported CSS propertiesassets/example-template.tsx - Minimal working example demonstrating fixed footers, page numbers, and unbreakable content. Read this before starting to understand the basic patterns. Note: not all APIs are shown here — always refer to the docs and references/components.md for the full API.npm install react @react-pdf/renderer
npm install -D tsx @types/react
tsx runs TypeScript + JSX files directly via Node with no config — no tsconfig.json needed. It uses esbuild under the hood and handles JSX transformation automatically.
For full component props and CSS properties, see references/components.md.
import React from "react";
import { Document, Page, Text, View, StyleSheet, renderToFile } from "@react-pdf/renderer";
const styles = StyleSheet.create({
page: { flexDirection: "column", backgroundColor: "#ffffff", padding: 40 },
title: { fontSize: 24, marginBottom: 20, fontWeight: "bold" },
text: { fontSize: 12, lineHeight: 1.5 },
});
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={{ margin: 10, padding: 20 }}>
<Text style={styles.title}>Document Title</Text>
<Text style={styles.text}>Your content here</Text>
</View>
</Page>
</Document>
);
(async () => {
await renderToFile(<MyDocument />, "./output.pdf");
console.log("PDF saved!");
})();
PDF generation scripts use JSX, which Node cannot run directly. Use tsx to execute them:
npx tsx my-document.tsx
npx tsx works without installing tsx globally — it downloads on demand. If tsx is installed as a dev dependency (npm install -D tsx), it runs instantly without the npx download step.
Always wrap rendering in async IIFE:
// Good
(async () => {
await renderToFile(<MyDocument />, "./output.pdf");
})();
// Bad - top-level await may fail
await renderToFile(<MyDocument />, "./output.pdf");
To visually inspect generated PDFs, convert pages to images. Try pdftoppm first (often pre-installed), fall back to Python's PyMuPDF if unavailable.
Option 1: pdftoppm (poppler-utils) — preferred, no install needed in many environments:
pdftoppm -png -r 200 document.pdf preview
# → preview-1.png, preview-2.png, ...
Option 2: PyMuPDF (Python) — fallback if pdftoppm is not available:
pip install pymupdf
import fitz
doc = fitz.open("document.pdf")
for i, page in enumerate(doc):
pix = page.get_pixmap(dpi=200)
pix.save(f"page-{i+1}.png")
import { renderToFile, renderToBuffer } from "@react-pdf/renderer";
// To file
(async () => {
await renderToFile(<MyDocument />, "./document.pdf");
})();
// To buffer
(async () => {
const buffer = await renderToBuffer(<MyDocument />);
})();
Three methods: StyleSheet.create(), inline objects, or mixed arrays.
const styles = StyleSheet.create({ container: { padding: 20 } });
<View style={styles.container} />
<View style={{ padding: 20 }} />
<View style={[styles.container, { marginTop: 10 }]} />
pt (default, 72 DPI), in, mm, cm, %, vw, vh
{
// Flexbox
flexDirection: "row", justifyContent: "space-between", alignItems: "center",
flexWrap: "wrap", gap: 10,
// Box model
margin: 10, padding: 20, width: "100%", height: 200,
// Borders
borderWidth: 1, borderColor: "#333", borderRadius: 5, borderStyle: "solid",
// Colors
backgroundColor: "#f0f0f0", color: "#000", opacity: 0.8,
// Typography
fontSize: 12, fontWeight: "bold", fontFamily: "Helvetica", fontStyle: "italic",
lineHeight: 1.5, textAlign: "center", textDecoration: "underline",
textTransform: "uppercase", letterSpacing: 1,
// Position
position: "absolute", top: 0, left: 0, right: 0, bottom: 0, zIndex: 10,
// Transforms
transform: "rotate(45deg)", transformOrigin: "center",
}
Local files are most reliable. Remote URLs may fail due to network/CORS issues.
import { Image } from '@react-pdf/renderer';
<Image src="./images/photo.jpg" style={{ width: 200, height: 150 }} />
<Image src={{ data: buffer, format: 'png' }} />
SVG files cannot be used as Image sources. Read the SVG source and recreate using react-pdf Svg components.
import { Svg, Circle, Rect, Path, Line, G, Defs, LinearGradient, Stop } from "@react-pdf/renderer";
<Svg width="200" height="200" viewBox="0 0 200 200">
<Defs>
<LinearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#3498db" />
<Stop offset="100%" stopColor="#9b59b6" />
</LinearGradient>
</Defs>
<Circle cx="100" cy="100" r="50" fill="url(#grad1)" />
<Rect x="10" y="10" width="50" height="50" fill="#e74c3c" />
<Path d="M10,50 Q50,10 90,50" stroke="#2ecc71" strokeWidth="2" fill="none" />
</Svg>;
Read SVG source from icon libraries and convert to react-pdf Svg components:
npm install lucide-static
import { Svg, Path, Rect } from "@react-pdf/renderer";
// Converted from lucide-static/icons/mail.svg
const MailIcon = ({ size = 12, color = "#888" }) => (
<Svg width={size} height={size} viewBox="0 0 24 24">
<Path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7" stroke={color} strokeWidth={2} fill="none" />
<Rect x="2" y="4" width="20" height="16" rx="2" stroke={color} strokeWidth={2} fill="none" />
</Svg>
);
<Link src="https://example.com"><Text>Visit website</Text></Link>
<View id="section-1"><Text>Target</Text></View>
<Link src="#section-1"><Text>Jump to Section 1</Text></Link>
<Text render={({ pageNumber, totalPages }) => `Page ${pageNumber} of ${totalPages}`} />
<Page size="A4">
<View fixed style={{ position: "absolute", top: 20, left: 30, right: 30 }}>
<Text>Header</Text>
</View>
<View style={{ marginTop: 60, marginBottom: 60 }}>
<Text>Content</Text>
</View>
<Text
fixed
style={{ position: "absolute", bottom: 20, left: 30, right: 30, textAlign: "center" }}
render={({ pageNumber, totalPages }) => `Page ${pageNumber} of ${totalPages}`}
/>
</Page>
<View break /> // Force page break
<View wrap={false}><Text>Keep together</Text></View> // Prevent breaking inside
<Text orphans={2} widows={2}>Long text...</Text> // Orphan/widow control
<View minPresenceAhead={100}><Text>Content</Text></View> // Min space before break
CRITICAL: All font sources MUST be local file paths. Remote URLs do not work.
import { Font } from "@react-pdf/renderer";
Font.register({
family: "Roboto",
fonts: [
{ src: "./fonts/Roboto-Regular.ttf", fontWeight: "normal" },
{ src: "./fonts/Roboto-Bold.ttf", fontWeight: "bold" },
{ src: "./fonts/Roboto-Italic.ttf", fontStyle: "italic" },
],
});
// Always disable hyphenation when using custom fonts
Font.registerHyphenationCallback((word) => [word]);
Built-in fonts : Courier, Helvetica, Times-Roman (each with Bold, Italic/Oblique variants)
Font weight values : thin (100), ultralight (200), light (300), normal (400), medium (500), semibold (600), bold (700), ultrabold (800), heavy (900)
Use references/google-fonts.txt to find font URLs, then download locally:
# Find the font URL
grep "^Roboto" skills/react-pdf/references/google-fonts.txt | grep "700" | grep "normal"
# Download
mkdir -p fonts
curl -sL "<url-from-grep>" -o fonts/Roboto-Bold.ttf
# Verify - must show "TrueType Font data"
file fonts/Roboto-Bold.ttf
If file shows "HTML document" or "ASCII text", the download failed. Try a different URL or search GitHub for the font's official repo with TTF files.
Emoji won't render in PDFs unless you register an emoji source. Install twemoji-emojis to get local Twemoji PNG assets — no internet needed at render time.
npm install twemoji-emojis
import { Font } from "@react-pdf/renderer";
Font.registerEmojiSource({
format: "png",
url: "node_modules/twemoji-emojis/vendor/72x72/",
});
Then use emoji directly in Text: <Text>Hello 🚀🎉</Text>
// Canvas drawing
<Canvas style={{ width: 200, height: 200 }}
paint={(painter, w, h) => { painter.circle(w/2, h/2, 50).fill("#3498db"); }} />
// Annotation notes
<Note style={{ color: "yellow" }}>Annotation text</Note>
// Hyphenation
Font.registerHyphenationCallback((word) => [word]); // disable
// Debug mode - visualize boundaries
<View debug><Text debug>Debug text</Text></View>
// Document metadata
<Document title="My Doc" author="Author" subject="Report" language="en-US" pdfVersion="1.5" />
StyleSheet.create() — define styles once and reusecache={true} for remote imagesfixed prop for headers/footers on every pagedebug={true} to visualize element boundariesText overflow : <Text style={{ width: 200, maxLines: 3, textOverflow: "ellipsis" }}>...</Text>
Missing fonts : Download locally and register with local file paths. Remote URLs will NOT work.
Unexpected page breaks : Use wrap={false} to keep content together, or <View break /> to force breaks.
Weekly Installs
263
Repository
GitHub Stars
134
First Seen
Feb 12, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode239
gemini-cli232
codex229
github-copilot216
amp207
kimi-cli206
Flutter应用架构设计指南:分层结构、数据层实现与最佳实践
3,400 周安装
macOS磁盘清理工具 - 安全智能分析回收存储空间 | macOS Cleaner
257 周安装
PPT模板创建器:将PowerPoint模板转化为可复用技能,自动化演示文稿生成
257 周安装
商务邮件草拟助手:AI智能生成专业邮件模板,提升办公沟通效率
257 周安装
Docassemble 表单构建器技能 - 创建智能动态问卷与文档生成工具
257 周安装
Fastify TypeScript 生产级后端框架指南:高性能 Node.js Web 开发与 JSON 模式验证
257 周安装
AI 演示文稿生成器 | 一键创建专业幻灯片,支持 Marp 格式输出
257 周安装