th commited on
Commit
bebd683
·
1 Parent(s): 97018c0

Improve PDF rendering and document integration

Browse files
Files changed (3) hide show
  1. README.md +13 -1
  2. app.py +27 -3
  3. docs/branded-report-pdf-playbook.md +332 -0
README.md CHANGED
@@ -41,10 +41,22 @@ Generate PDF from HTML and return as binary file.
41
  "margin_left": "20mm",
42
  "margin_right": "20mm",
43
  "print_background": true,
44
- "landscape": false
 
 
45
  }
46
  ```
47
 
 
 
 
 
 
 
 
 
 
 
48
  **Response**: PDF binary file
49
 
50
  ### `POST /generate-pdf-base64`
 
41
  "margin_left": "20mm",
42
  "margin_right": "20mm",
43
  "print_background": true,
44
+ "landscape": false,
45
+ "prefer_css_page_size": false,
46
+ "render_timeout_ms": 30000
47
  }
48
  ```
49
 
50
+ For branded multi-page reports, set all API margins to `0`, enable
51
+ `prefer_css_page_size`, and define page margins in the HTML `@page` CSS.
52
+
53
+ ## Branded report integration
54
+
55
+ See [docs/branded-report-pdf-playbook.md](docs/branded-report-pdf-playbook.md)
56
+ for the reusable Astrology Bazi workflow: deterministic HTML templates,
57
+ Cloudflare server-side proxying, embedded logos, full-bleed covers, pagination,
58
+ and visual PDF verification.
59
+
60
  **Response**: PDF binary file
61
 
62
  ### `POST /generate-pdf-base64`
app.py CHANGED
@@ -59,6 +59,29 @@ class PDFRequest(BaseModel):
59
  margin_right: Optional[str] = "20mm"
60
  print_background: Optional[bool] = True
61
  landscape: Optional[bool] = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
 
64
  @app.get("/")
@@ -119,12 +142,12 @@ async def generate_pdf(request: PDFRequest, api_key: str = Depends(verify_api_ke
119
  # Create new page
120
  page = await browser.new_page()
121
 
122
- # Set content
123
- await page.set_content(request.html_content, wait_until='networkidle')
124
 
125
  # Generate PDF
126
  pdf_bytes = await page.pdf(
127
  format=request.page_size,
 
128
  print_background=request.print_background,
129
  landscape=request.landscape,
130
  margin={
@@ -174,10 +197,11 @@ async def generate_pdf_base64(request: PDFRequest, api_key: str = Depends(verify
174
  )
175
 
176
  page = await browser.new_page()
177
- await page.set_content(request.html_content, wait_until='networkidle')
178
 
179
  pdf_bytes = await page.pdf(
180
  format=request.page_size,
 
181
  print_background=request.print_background,
182
  landscape=request.landscape,
183
  margin={
 
59
  margin_right: Optional[str] = "20mm"
60
  print_background: Optional[bool] = True
61
  landscape: Optional[bool] = False
62
+ prefer_css_page_size: Optional[bool] = False
63
+ render_timeout_ms: Optional[int] = 30000
64
+
65
+
66
+ async def prepare_page(page, request: PDFRequest):
67
+ """Load HTML and wait for print assets before Chromium snapshots the page."""
68
+ timeout = max(5000, min(request.render_timeout_ms or 30000, 60000))
69
+ await page.emulate_media(media="print")
70
+ await page.set_content(request.html_content, wait_until="networkidle", timeout=timeout)
71
+ await page.evaluate("document.fonts.ready")
72
+ await page.evaluate(
73
+ """
74
+ async () => {
75
+ await Promise.all([...document.images].map((image) => {
76
+ if (image.complete) return Promise.resolve();
77
+ return new Promise((resolve) => {
78
+ image.addEventListener('load', resolve, { once: true });
79
+ image.addEventListener('error', resolve, { once: true });
80
+ });
81
+ }));
82
+ }
83
+ """
84
+ )
85
 
86
 
87
  @app.get("/")
 
142
  # Create new page
143
  page = await browser.new_page()
144
 
145
+ await prepare_page(page, request)
 
146
 
147
  # Generate PDF
148
  pdf_bytes = await page.pdf(
149
  format=request.page_size,
150
+ prefer_css_page_size=request.prefer_css_page_size,
151
  print_background=request.print_background,
152
  landscape=request.landscape,
153
  margin={
 
197
  )
198
 
199
  page = await browser.new_page()
200
+ await prepare_page(page, request)
201
 
202
  pdf_bytes = await page.pdf(
203
  format=request.page_size,
204
+ prefer_css_page_size=request.prefer_css_page_size,
205
  print_background=request.print_background,
206
  landscape=request.landscape,
207
  margin={
docs/branded-report-pdf-playbook.md ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 品牌化命理报告 PDF 复用指南
2
+
3
+ 这份文档记录 Sparksverse 各类命理 App 生成品牌化 PDF 的标准方案。目标是让新 App 复用同一条稳定链路,不增加 AI 输出 token,也不让模型承担 HTML、CSS 或分页工作。
4
+
5
+ ## 1. 标准架构
6
+
7
+ ```text
8
+ 命理计算 API
9
+ ↓
10
+ AI 生成结构化报告 JSON
11
+ ↓
12
+ App 内固定 TypeScript HTML 模板
13
+ ↓
14
+ App 服务端 PDF 代理
15
+ ↓
16
+ Sisi PDF API / Playwright Chromium
17
+ ↓
18
+ A4 PDF Blob 下载
19
+ ```
20
+
21
+ 职责必须分开:
22
+
23
+ - 计算 API 负责八字、紫微等确定性盘面数据。
24
+ - AI 只返回结构化内容,不生成 HTML、CSS、Logo 或分页标记。
25
+ - App 的模板函数负责转义数据、品牌样式和章节结构。
26
+ - PDF API 只负责渲染,不理解报告业务。
27
+
28
+ 这样调整背景、Logo、字体和分页时完全不消耗 AI token。
29
+
30
+ ## 2. 推荐文件结构
31
+
32
+ 每个 App 采用以下结构:
33
+
34
+ ```text
35
+ app/<product>/
36
+ components/<Product>ReportView.tsx
37
+ services/pdfService.ts
38
+ types.ts
39
+ functions/api/<product>-pdf.ts
40
+ public/<brand-logo>.png
41
+ ```
42
+
43
+ `pdfService.ts` 建议导出两个函数:
44
+
45
+ ```ts
46
+ export function buildProductPDFHTML(
47
+ options: ProductPDFOptions,
48
+ logoDataUrl: string,
49
+ ): string
50
+
51
+ export async function downloadProductPDF(
52
+ options: ProductPDFOptions,
53
+ ): Promise<void>
54
+ ```
55
+
56
+ 第一个函数保持纯函数,方便用假数据生成 HTML 和做视觉回归测试。第二个函数负责读取 Logo、调用站内代理和下载 Blob。
57
+
58
+ ## 3. 品牌视觉基线
59
+
60
+ 当前“天机玄鉴”报告使用:
61
+
62
+ | Token | Value | Usage |
63
+ |---|---:|---|
64
+ | Ink | `#171612` | 封面、结论页、重点结论 |
65
+ | Paper | `#f5f1e7` | 正文纸面与页边区域 |
66
+ | Ivory | `#fcfaf4` | 轻量内容区 |
67
+ | Gold | `#b89432` | 标题、细线、关键数字 |
68
+ | Gold highlight | `#d8ba5c` | 黑底上的金色内容 |
69
+ | Text | `#171612` | 正文 |
70
+ | Muted | `#6d675d` | 命盘依据和辅助信息 |
71
+ | Risk | `#7b3532` | 少量真实风险提示 |
72
+
73
+ 视觉原则:
74
+
75
+ - 黑金仅用于封面、关键结论和结束页,不做十几页黑底。
76
+ - 正文用象牙纸色,页边区域必须与正文同色,不能出现白色外框。
77
+ - Logo 是品牌锚点,不做高透明度满页重复水印。
78
+ - 金色覆盖面积保持克制,优先使用细线、标签和关键数字。
79
+ - 三路径、时间窗口等需要比较的信息优先使用表格或时间轴,不堆叠卡片。
80
+
81
+ ## 4. Chromium 分页规则
82
+
83
+ 推荐基础规则:
84
+
85
+ ```css
86
+ @page {
87
+ size: A4 portrait;
88
+ margin: 17mm 18mm 20mm;
89
+ background: #f5f1e7;
90
+ }
91
+
92
+ @page:first {
93
+ margin: 0;
94
+ background: #171612;
95
+ }
96
+
97
+ .cover {
98
+ width: 210mm;
99
+ min-height: 297mm;
100
+ break-after: page;
101
+ }
102
+
103
+ .chapter {
104
+ break-before: page;
105
+ orphans: 3;
106
+ widows: 3;
107
+ }
108
+
109
+ .avoid-break {
110
+ break-inside: avoid;
111
+ }
112
+ ```
113
+
114
+ 关键经验:
115
+
116
+ 1. 不要使用命名 `@page cover`。Chromium 在复杂分页中可能插入空白页。
117
+ 2. 使用 `@page:first` 做满版封面。
118
+ 3. `@page` 必须设置纸张背景,否则 margin 区域会显示成白框。
119
+ 4. 不要让结束页使用 `min-height: 297mm` 加负 margin,容易溢出残页。
120
+ 5. 时间轴节点、行动计划和风险块使用 `break-inside: avoid`。
121
+ 6. 不要给所有父级容器都加 `break-inside: avoid`,否则会留下大段空白。
122
+ 7. 动态长文本必须允许自然分页,不能依赖固定高度裁切内容。
123
+
124
+ ## 5. Logo 与字体
125
+
126
+ ### Logo
127
+
128
+ 本地文件路径无法被远程 Hugging Face Space 读取。推荐在浏览器生成 HTML 前把 Logo 转成 data URI:
129
+
130
+ ```ts
131
+ async function getLogoDataUrl(path: string): Promise<string> {
132
+ const response = await fetch(path)
133
+ if (!response.ok) throw new Error('Unable to load report logo')
134
+ const blob = await response.blob()
135
+
136
+ return await new Promise((resolve, reject) => {
137
+ const reader = new FileReader()
138
+ reader.onload = () => resolve(String(reader.result))
139
+ reader.onerror = () => reject(reader.error)
140
+ reader.readAsDataURL(blob)
141
+ })
142
+ }
143
+ ```
144
+
145
+ 优先顺序:data URI > 自有 CDN URL > 第三方字体或图片 URL。
146
+
147
+ ### 字体
148
+
149
+ 当前 Docker 已安装 Noto CJK 字体。推荐字体栈:
150
+
151
+ ```css
152
+ /* Chinese */
153
+ font-family: "Noto Serif CJK SC", "Noto Serif SC",
154
+ "Source Han Serif SC", "Songti SC", serif;
155
+
156
+ /* English */
157
+ font-family: Charter, Georgia, "Times New Roman", serif;
158
+ ```
159
+
160
+ 不要只写浏览器本地字体名称。Hugging Face 容器中未安装的字体会静默 fallback。
161
+
162
+ ## 6. HTML 安全
163
+
164
+ 所有 AI 或用户文本进入模板前必须转义:
165
+
166
+ ```ts
167
+ const escapeHTML = (value: unknown): string => String(value ?? '')
168
+ .replace(/&/g, '&amp;')
169
+ .replace(/</g, '&lt;')
170
+ .replace(/>/g, '&gt;')
171
+ .replace(/"/g, '&quot;')
172
+ .replace(/'/g, '&#039;')
173
+ ```
174
+
175
+ 不要把模型返回内容作为原始 HTML 注入模板。列表应由数组映射生成,分数和百分比应在模板层限制到 `0–100`。
176
+
177
+ ## 7. Cloudflare 服务端代理
178
+
179
+ 浏览器不能直接持有 PDF API key。每��� App 应通过 Cloudflare Pages Function 转发:
180
+
181
+ ```ts
182
+ interface Env {
183
+ SISI_HF_API_KEY: string
184
+ PDF_API_URL?: string
185
+ }
186
+
187
+ export async function onRequestPost(context: { env: Env; request: Request }) {
188
+ const { html, fileName } = await context.request.json() as {
189
+ html?: string
190
+ fileName?: string
191
+ }
192
+
193
+ if (!html) return new Response('Missing PDF HTML', { status: 400 })
194
+
195
+ const response = await fetch(
196
+ `${context.env.PDF_API_URL || 'https://sisithefox-sisi-pdf-api.hf.space'}/generate-pdf`,
197
+ {
198
+ method: 'POST',
199
+ headers: {
200
+ 'Content-Type': 'application/json',
201
+ 'x-api-key': context.env.SISI_HF_API_KEY,
202
+ },
203
+ body: JSON.stringify({
204
+ html_content: html,
205
+ filename: fileName || 'report.pdf',
206
+ page_size: 'A4',
207
+ margin_top: '0',
208
+ margin_bottom: '0',
209
+ margin_left: '0',
210
+ margin_right: '0',
211
+ print_background: true,
212
+ prefer_css_page_size: true,
213
+ }),
214
+ },
215
+ )
216
+
217
+ if (!response.ok) return new Response('Unable to generate PDF', { status: 502 })
218
+ return new Response(response.body, {
219
+ headers: {
220
+ 'Content-Type': 'application/pdf',
221
+ 'Cache-Control': 'no-store',
222
+ },
223
+ })
224
+ }
225
+ ```
226
+
227
+ Cloudflare 环境变量统一使用 `SISI_HF_API_KEY`。不要为新 App 增加 `NEXT_PUBLIC_SISI_HF_API_KEY`。
228
+
229
+ 代理至少需要:
230
+
231
+ - 限制 HTML 请求大小,当前建议 `2MB`。
232
+ - 清理 `Content-Disposition` 文件名中的引号、反斜线和换行。
233
+ - 返回 `Cache-Control: no-store`。
234
+ - 不在日志中输出完整 HTML 或报告正文。
235
+
236
+ ## 8. PDF API 请求参数
237
+
238
+ 标准请求:
239
+
240
+ ```json
241
+ {
242
+ "html_content": "<!doctype html>...",
243
+ "filename": "private-report.pdf",
244
+ "page_size": "A4",
245
+ "margin_top": "0",
246
+ "margin_bottom": "0",
247
+ "margin_left": "0",
248
+ "margin_right": "0",
249
+ "print_background": true,
250
+ "landscape": false,
251
+ "prefer_css_page_size": true,
252
+ "render_timeout_ms": 30000
253
+ }
254
+ ```
255
+
256
+ `prefer_css_page_size: true` 让 HTML 中的 `@page` 决定纸张和页边距。API 在截图前必须:
257
+
258
+ 1. 使用 print media。
259
+ 2. 等待 `networkidle`。
260
+ 3. 等待 `document.fonts.ready`。
261
+ 4. 等待所有图片成功或失败完成。
262
+
263
+ ## 9. 下载按钮状态
264
+
265
+ 报告页面需要完整状态:
266
+
267
+ - 默认:`下载典藏版 PDF`
268
+ - 生成中:`正在排版...`
269
+ - 禁用按钮,防止重复请求
270
+ - 失败:显示可重试错误,不丢失网页报告
271
+
272
+ 网页中的“保存 PDF”按钮不再调用 `window.print()`。浏览器打印只能作为开发调试手段,不能作为付费报告交付方式。
273
+
274
+ ## 10. 验证流程
275
+
276
+ 每次新增或修改模板必须完成以下检查:
277
+
278
+ ```bash
279
+ # App 类型检查
280
+ npm run typecheck
281
+
282
+ # Python API 语法检查,不生成 __pycache__
283
+ python3 -c "import ast, pathlib; ast.parse(pathlib.Path('app.py').read_text())"
284
+
285
+ # PDF 信息
286
+ pdfinfo /tmp/report.pdf
287
+
288
+ # PDF 转图片
289
+ pdftoppm -png -r 110 /tmp/report.pdf /tmp/report-page
290
+
291
+ # 生成页面缩略图总览
292
+ montage /tmp/report-page-*.png \
293
+ -thumbnail 320x -tile 2x4 -geometry +12+12 \
294
+ -background '#d7d2c6' /tmp/report-contact.png
295
+ ```
296
+
297
+ 视觉检查必须确认:
298
+
299
+ - 没有封面前空白页或结尾残页。
300
+ - Logo 清晰且没有拉伸。
301
+ - 页边区域没有白框。
302
+ - 中文字体没有方框或异常 fallback。
303
+ - 表格没有文字重叠或横向溢出。
304
+ - 长段落没有被固定高度裁切。
305
+ - 章节标题没有独自留在上一页底部。
306
+ - PDF 页数和文件体积合理。
307
+
308
+ ## 11. 新 App 接入清单
309
+
310
+ 1. 定义稳定的报告 JSON type。
311
+ 2. 建立纯函数 HTML 模板。
312
+ 3. 复制品牌 tokens,而不是复制整个旧报告组件。
313
+ 4. 添加产品特有的章节布局。
314
+ 5. 将 Logo 放入 `public/` 并转换为 data URI。
315
+ 6. 新增 Cloudflare PDF 代理,读取 `SISI_HF_API_KEY`。
316
+ 7. 接入下载按钮的 loading/error 状态。
317
+ 8. 用中英文假数据各生成一份 PDF。
318
+ 9. 用 Poppler 渲染全部页面做视觉检查。
319
+ 10. 分别部署 PDF API 和 App。
320
+
321
+ ## 12. 参考实现
322
+
323
+ 当前完整实现位于 astrologybazi:
324
+
325
+ ```text
326
+ app/life-path-reading/services/pdfService.ts
327
+ app/life-path-reading/components/LifePathReportView.tsx
328
+ functions/api/life-path-pdf.ts
329
+ public/bazi-logo-cn.png
330
+ ```
331
+
332
+ 后续 App 应复用架构和视觉 tokens,但根据自身报告内容重新设计章节,不要机械复制 Life Path 的三路径表。