zcode-app-cli 3.3.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,1659 @@
1
+ # Brief: Report Production
2
+
3
+ Structured documents via ReportLab: reports, proposals, contracts, white papers, financial analysis, data tables. Also covers ATS-friendly resumes.
4
+
5
+ ---
6
+
7
+ > ### 🚨 EMOJI CHECK - STOP HERE IF CONTENT HAS EMOJI
8
+ >
9
+ > ReportLab renders emoji (📊🎯🔥💡 etc.) as **□ tofu squares**. This is unfixable.
10
+ >
11
+ > **If the user's content contains intentional emoji** → **STOP. Do NOT use this brief.**
12
+ > Route to `briefs/creative.md` instead (Playwright renders emoji natively).
13
+ >
14
+ > This applies even if the document is a "report" - emoji + ReportLab = broken output.
15
+
16
+ ---
17
+
18
+ ## Production Workflow
19
+
20
+ ```
21
+ 1. BRIEF → Confirm document type, audience, page count, outline
22
+ 2. DESIGN → Run `pdf.py palette.generate --title "..."` → copy-paste output into script
23
+ 3. EDIT → Content transformation (extract data, define typographic roles)
24
+ 4. COVER → Read typesetting/cover.md → render HTML cover via Playwright (default ON for reports ≥ 3 pages; skip only for resumes/letters/memos/forms)
25
+ 5. BUILD → Write ReportLab code (fonts → styles → content → tables → charts)
26
+ 6. PREFLIGHT → code.sanitize → execute → meta.brand → font.check → toc.check → pages.clean → pdf_qa.py
27
+ 7. DELIVER → Merge cover + body → final PDF
28
+ ```
29
+
30
+ **Typesetting assets** (load when you reach that step):
31
+ - `typesetting/palette.md` - color system, typography rules, anti-patterns
32
+ - `typesetting/cover.md` - 7 cover layouts with variants, typography scale, bounding box rules
33
+ - `typesetting/charts.md` - chart styling, anti-stacking rules, axis/grid/legend treatment
34
+
35
+ **Cover is DEFAULT ON for reports.** Skip cover only for: resumes, letters, memos, forms, checklists, or documents ≤ 2 pages.
36
+
37
+ ---
38
+
39
+ ## Step 2: DESIGN - Palette & Font Plan
40
+
41
+ **Before writing any ReportLab code, you MUST generate the color palette via the `palette.generate` command.** This is not optional. Do NOT hardcode hex colors. Do NOT pick colors by feel.
42
+
43
+ ### 2a. Generate Palette (MANDATORY)
44
+
45
+ **Run this command FIRST. Copy-paste its output directly into your Python script:**
46
+
47
+ ```bash
48
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" palette.generate --title "<document title>" --mode minimal
49
+ ```
50
+
51
+ The command auto-derives the design intent from the document title, computes a mathematically harmonious palette, and outputs ready-to-paste ReportLab Python code:
52
+
53
+ ```python
54
+ # ━━ Color Palette (auto-generated by pdf.py palette.generate) ━━
55
+ # Intent: neutral | Mode: minimal | Harmony: split_complementary
56
+ # Contrast: text:bg=14.12 | accent:bg=3.06
57
+ from reportlab.lib import colors
58
+ ACCENT = colors.HexColor('#2f97b9')
59
+ TEXT_PRIMARY = colors.HexColor('#252422')
60
+ TEXT_MUTED = colors.HexColor('#8d8981')
61
+ BG_SURFACE = colors.HexColor('#dfdad2')
62
+ BG_PAGE = colors.HexColor('#f5f4f3')
63
+ SURFACE_RGBA = 'rgba(0,0,0,0.03)'
64
+
65
+ # ReportLab table colors
66
+ TABLE_HEADER_COLOR = ACCENT
67
+ TABLE_HEADER_TEXT = colors.white
68
+ TABLE_ROW_EVEN = colors.white
69
+ TABLE_ROW_ODD = BG_SURFACE
70
+ ```
71
+
72
+ **Options:**
73
+ - `--mode minimal` (default, recommended for 50%+ of documents) | `dark` | `pastel` | `jewel` | `light`
74
+ - `--harmony auto` (default, recommended) | `complementary` | `split_complementary` | `analogous` | `triadic` | `monochrome`
75
+ - `--format python` (default) | `json` | `css`
76
+ - `--seed <int>` - for reproducible palettes across regenerations
77
+
78
+ **⚠️ FORBIDDEN:**
79
+ - ❌ Writing `colors.HexColor('#xxxxxx')` with any hex value you chose yourself
80
+ - ❌ Using `colors.red`, `colors.blue`, or any ReportLab named color for design elements
81
+ - ❌ Skipping this step and picking colors "that look good"
82
+ - ❌ Using different palettes for different sections of the same document
83
+
84
+ **✅ The ONLY acceptable way to get colors:** Run `palette.generate`, copy the output.
85
+
86
+ ### 2b. Color Application Rules
87
+
88
+ | Element | Color Source | Notes |
89
+ |---------|-------------|-------|
90
+ | Table headers | ACCENT (bg) + white (text) | High contrast required |
91
+ | Table odd rows | BG_SURFACE at 50% opacity | Subtle striping |
92
+ | Section titles | ACCENT or TEXT_PRIMARY | Match heading hierarchy |
93
+ | Body text | TEXT_PRIMARY | Never use pure #000000 |
94
+ | Muted/meta text | TEXT_MUTED | Dates, captions, footnotes |
95
+ | Horizontal rules | ACCENT at 30% opacity | Thin, unobtrusive |
96
+ | Chart colors | Derive from ACCENT (see charts.md) | Consistent with palette |
97
+
98
+ ### 2c. Forbidden
99
+
100
+ - ❌ Hardcoding hex colors like `#1F4E79`, `#555555`, `#888888` in code
101
+ - ❌ Using `colors.red`, `colors.blue` or any ReportLab named color for design elements
102
+ - ❌ Choosing colors by "feel" without running palette first
103
+ - ❌ Using different accent colors across tables/sections in the same document
104
+
105
+ > **Exception**: Semantic colors for data visualization (green for positive, red for negative) are acceptable but should be muted variants derived from the palette when possible.
106
+
107
+ ---
108
+
109
+ ## Step 3: EDIT - Content Transformation
110
+
111
+ **Before writing any code, restructure raw text into visual roles.** This is the most impactful quality step - skipping it produces "Word document with a PDF extension".
112
+
113
+ ### 3a. Typographic Role Extraction
114
+
115
+ Parse raw text and categorize content into visual roles:
116
+
117
+ | Role | ReportLab Mapping | Description |
118
+ |------|------------------|-------------|
119
+ | **Hero / Display** | Cover title (36-42pt) or section opener | 1-5 words, the emotional hook |
120
+ | **Kicker / Eyebrow** | Subtitle or section intro (10-12pt, muted) | Tiny context line above main heading |
121
+ | **Data Sculpture** | CalloutBox or bold stat block | Extract impactful numbers (97%, $4.2M, -45ms) |
122
+ | **Pull Quote** | BlockQuote (italic + left indent 24pt + accent border) | Most provocative sentence, standalone |
123
+ | **Body** | Standard paragraph | Everything else |
124
+
125
+ **Rule**: Before writing any body paragraph, scan for numbers with units. Every metric like "revenue grew by 12%" or "latency dropped to 45ms" MUST be extracted into a CalloutBox or metrics table - never buried in paragraph prose. See §Data-to-Ink Ratio Rules below.
126
+
127
+ ### 3b. Section Pacing
128
+
129
+ - If any H1 section has **>400 words** of continuous body text without visual breaks, split into H2 subsections or insert a visual break (table, chart, callout)
130
+ - Aim for at least 1 visual element (table/chart/callout) per 2-3 pages of body text
131
+ - Dense text walls are the #1 sign of poor report design
132
+
133
+ ---
134
+
135
+ ---
136
+
137
+ ## Character Safety Rule (MANDATORY)
138
+
139
+ Three rules for safe character handling in ReportLab PDFs:
140
+
141
+ **a) Superscripts and subscripts**: Use `<super>`/`<sub>` tags, never raw Unicode superscript/subscript characters (e.g., `\u00b2`, `\u2082`).
142
+
143
+ **b) Emoji**: ReportLab cannot render emoji. If content contains emoji, use Creative brief (HTML + Playwright).
144
+
145
+ **c) Font fallback for mixed CJK/Latin text**: After registering fonts, call `install_font_fallback()` once. This automatically wraps missing-glyph characters in `<font>` tags inside every `Paragraph()`. No manual `<font name="...">` wrapping needed for mixed Chinese-English text.
146
+
147
+ Mathematical/relational operators (×, ÷, ±, ≤, √, ∑, ≅, ∫, π, ∠, Δ, etc.) are safe to use as literal characters in `Paragraph()` - both SimHei and Times New Roman have these glyphs.
148
+
149
+ | Need | Correct Method | Correct Example |
150
+ |------|---------------|---------|
151
+ | Superscript | `<super>` tag in `Paragraph()` | `Paragraph('10<super>2</super> × 10<super>3</super> = 10<super>5</super>', style)` |
152
+ | Subscript | `<sub>` tag in `Paragraph()` | `Paragraph('H<sub>2</sub>O', style)` |
153
+ | Bold | `<b>` tag in `Paragraph()` | `Paragraph('<b>Title</b>', style)` |
154
+ | Math operators | Literal char in `Paragraph()` | `Paragraph('AB ⊥ AC, ∠A = 90°, and ΔABC ≅ ΔDCF', style)` |
155
+ | Scientific notation | Combined tags in `Paragraph()` | `Paragraph('1.2 × 10<super>8</super> kg/m<super>3</super>', style)` |
156
+
157
+ ```python
158
+ from reportlab.platypus import Paragraph
159
+ from reportlab.lib.styles import ParagraphStyle
160
+ from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
161
+
162
+ body_style = ParagraphStyle(
163
+ name="ENBodyStyle",
164
+ fontName="Times New Roman",
165
+ fontSize=10.5,
166
+ leading=18,
167
+ alignment=TA_JUSTIFY,
168
+ )
169
+
170
+ # Superscript: area unit
171
+ Paragraph('Total area: 500 m<super>2</super>', body_style)
172
+
173
+ # Subscript: chemical formula
174
+ Paragraph('The reaction produces CO<sub>2</sub> and H<sub>2</sub>O', body_style)
175
+
176
+ # Scientific notation
177
+ Paragraph('Speed of light: 3.0 × 10<super>8</super> m/s', body_style)
178
+
179
+ # Combined
180
+ Paragraph('E<sub>k</sub> = mv<super>2</super>/2', body_style)
181
+
182
+ # Bold heading
183
+ Paragraph('<b>Chapter 1: Introduction</b>', header_style)
184
+
185
+ # Math symbols
186
+ Paragraph('When ∠ A = 90°, AB ⊥ AC and ΔABC ≅ ΔDEF', body_style)
187
+ ```
188
+
189
+ **Pre-generation check - before writing ANY string, ask:**
190
+ > "Does this string contain a character outside basic CJK or Mathematical/relational operators?"
191
+ > If YES → it MUST be inside a `Paragraph()` with the appropriate tag.
192
+ > If it is a superscript/subscript digit in raw unicode escape form → REPLACE with `<super>`/`<sub>` tag.
193
+
194
+ **NEVER rely on post-generation scanning. Prevent at the point of writing.**
195
+
196
+ **Encoding safety - before writing ANY content text:**
197
+ > "Does this string contain Japanese kana (の, が, は etc.) or rare Unicode symbols?"
198
+ > If YES → REPLACE with safe plain Chinese equivalents. Japanese kana (Hiragana U+3040-U+309F, Katakana U+30A0-U+30FF) frequently corrupt to U+FFFD (�) when code passes through LLM output, heredoc, or terminal encoding layers.
199
+ > Common safe replacements: `活の真鲷`→`活缔真鲷`, `盐烤の鲭鱼`→`盐烤鲭鱼`, `烤の鸡串`→`炭烤鸡串`.
200
+ > If the character is genuinely needed, verify it survives a full write→read round-trip with `open(file, encoding='utf-8')`.
201
+
202
+ ---
203
+
204
+ ## Font Setup (Guaranteed Success Method)
205
+
206
+ ### CRITICAL: Allowed Fonts Only
207
+ **You MUST ONLY use the following registered fonts. Using ANY other font is STRICTLY FORBIDDEN.**
208
+
209
+ | Font Name | Usage | Path |
210
+ |-----------|-------|------|
211
+ | `Microsoft YaHei` | Chinese headings | `/usr/share/fonts/truetype/chinese/msyh.ttf` |
212
+ | `SimHei` | Chinese body text | `/usr/share/fonts/truetype/chinese/SimHei.ttf` |
213
+ | `SarasaMonoSC` | Chinese code blocks | `/usr/share/fonts/truetype/chinese/SarasaMonoSC-Regular.ttf` |
214
+ | `Times New Roman` | English text, numbers, tables | `/usr/share/fonts/truetype/english/Times-New-Roman.ttf` |
215
+ | `Calibri` | English alternative | `/usr/share/fonts/truetype/english/calibri-regular.ttf` |
216
+ | `DejaVuSans` | Formulas, symbols, code | `/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf` |
217
+
218
+ **FORBIDDEN fonts (DO NOT USE):**
219
+ - ❌ Arial, Arial-Bold, Arial-Italic
220
+ - ❌ Helvetica, Helvetica-Bold, Helvetica-Oblique
221
+ - ❌ Courier, Courier-Bold
222
+ - ❌ Any font not listed in the table above
223
+
224
+ ### Font Registration Template
225
+ ```python
226
+ from reportlab.pdfbase import pdfmetrics
227
+ from reportlab.pdfbase.ttfonts import TTFont
228
+ from reportlab.pdfbase.pdfmetrics import registerFontFamily
229
+
230
+ # Chinese fonts
231
+ pdfmetrics.registerFont(TTFont('Microsoft YaHei', '/usr/share/fonts/truetype/chinese/msyh.ttf'))
232
+ pdfmetrics.registerFont(TTFont('SimHei', '/usr/share/fonts/truetype/chinese/SimHei.ttf'))
233
+ pdfmetrics.registerFont(TTFont("SarasaMonoSC", '/usr/share/fonts/truetype/chinese/SarasaMonoSC-Regular.ttf'))
234
+
235
+ # English fonts
236
+ pdfmetrics.registerFont(TTFont('Times New Roman', '/usr/share/fonts/truetype/english/Times-New-Roman.ttf'))
237
+ pdfmetrics.registerFont(TTFont('Calibri', '/usr/share/fonts/truetype/english/calibri-regular.ttf'))
238
+
239
+ # Symbol/Formula font
240
+ pdfmetrics.registerFont(TTFont("DejaVuSans", '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'))
241
+
242
+ # CRITICAL: Register font families to enable <b>, <super>, <sub> tags
243
+ registerFontFamily('Microsoft YaHei', normal='Microsoft YaHei', bold='Microsoft YaHei')
244
+ registerFontFamily('SimHei', normal='SimHei', bold='SimHei')
245
+ registerFontFamily('Times New Roman', normal='Times New Roman', bold='Times New Roman')
246
+ registerFontFamily('Calibri', normal='Calibri', bold='Calibri')
247
+ registerFontFamily('DejaVuSans', normal='DejaVuSans', bold='DejaVuSans')
248
+ ```
249
+
250
+ ### Font Configuration by Document Type
251
+
252
+ **For Chinese PDFs:**
253
+ - Body text: `SimHei` or `Microsoft YaHei`
254
+ - Headings: `Microsoft YaHei` (MUST use for Chinese headings)
255
+ - Code blocks: `SarasaMonoSC`
256
+ - Formulas/symbols: `DejaVuSans`
257
+ - **In tables: ALL Chinese content and numbers MUST use `SimHei`**
258
+
259
+ **For English PDFs:**
260
+ - Body text: `Times New Roman`
261
+ - Headings: `Times New Roman` (MUST use for English headings)
262
+ - Code blocks: `DejaVuSans`
263
+ - **In tables: ALL English content and numbers MUST use `Times New Roman`**
264
+
265
+ **For Mixed Chinese-English PDFs:**
266
+ - Call `install_font_fallback()` once after registering fonts - it automatically wraps characters in `<font>` tags so you don't need to do it manually.
267
+ - If you still want manual control, you can use `<font name='...'>` tags, but the automatic fallback handles most cases.
268
+
269
+ ```python
270
+ import sys, os
271
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'scripts'))
272
+ from pdf import install_font_fallback
273
+
274
+ # 1. Register fonts (as above)
275
+ # 2. Install fallback - one line, handles all mixed-language text
276
+ install_font_fallback()
277
+
278
+ # 3. Just write naturally - no manual <font> wrapping needed!
279
+ en_style = ParagraphStyle(name="EN", fontName="Times New Roman", fontSize=10.5, leading=18)
280
+ cn_style = ParagraphStyle(name="CN", fontName="SimHei", fontSize=10.5, leading=18)
281
+
282
+ Paragraph('MySQL、PostgreSQL、Redis', en_style) # ✅ CJK comma auto-fallback to SimHei
283
+ Paragraph('Beijing (北京) has 21M people', en_style) # ✅ CJK chars auto-fallback
284
+ Paragraph('价格:¥2,200~5,800/月', en_style) # ✅ all CJK chars handled
285
+ Paragraph('《巴黎协定》签署于2015年', en_style) # ✅ CJK book title marks handled
286
+ ```
287
+
288
+ **How it works:** `install_font_fallback()` monkey-patches `Paragraph.__init__` to scan each character against the font's `charToGlyph` table. Characters missing from the base font are automatically wrapped in `<font name="FallbackFont">`. The fallback chain is: English fonts → SimHei, Chinese fonts → Times New Roman. For aesthetic optimization, Cyrillic text in SimHei is automatically routed to Times New Roman (serif looks better for Cyrillic).
289
+
290
+ ### Chinese Plot PNG Method
291
+ ```python
292
+ import matplotlib.pyplot as plt
293
+ plt.rcParams['font.sans-serif'] = ['SimHei']
294
+ plt.rcParams['axes.unicode_minus'] = False
295
+ ```
296
+
297
+ ### Available Font Paths
298
+ Run `fc-list` to get more fonts. Font files are typically located under:
299
+ - `/usr/share/fonts/truetype/chinese/`
300
+ - `/usr/share/fonts/truetype/english/`
301
+ - `/usr/share/fonts/`
302
+
303
+ ---
304
+
305
+ ## Layout & Spacing Control
306
+
307
+ ### Page Breaks
308
+
309
+ Follow the document type strategy defined in SOUL.md Rule 1.
310
+
311
+ **Structural breaks (always - MANDATORY):**
312
+ - Between cover page and TOC - **cover must NEVER share a page with anything else**
313
+ - Between TOC and main content
314
+ - Between main content and back cover
315
+
316
+ **Content breaks (by document type):**
317
+ - **Default (all document types)**: ❗ **Absolutely NEVER force page breaks before H1/H2** — content flows naturally, do not insert `PageBreak()` before section headings. This is an iron rule.
318
+ - Resume / contract / letter → No content page breaks
319
+ - Short article → No content page breaks
320
+ - **Exception 1**: Academic papers / textbooks / teaching plans → `PageBreak()` before each H1 is acceptable (only if user explicitly requests academic formatting)
321
+ - **Exception 2**: User explicitly requests page breaks between chapters
322
+
323
+ **Anti-tear (mandatory — but with height limit):**
324
+ ```python
325
+ from reportlab.platypus import KeepTogether
326
+ from reportlab.lib.pagesizes import A4
327
+ from reportlab.lib.units import inch
328
+
329
+ # Maximum height for KeepTogether blocks: 40% of page height
330
+ # Blocks taller than this should NOT be kept together — they cause
331
+ # the preceding page to be mostly empty when the block gets pushed down.
332
+ MAX_KEEP_HEIGHT = A4[1] * 0.4 # ~336pt ≈ 12cm
333
+
334
+ def safe_keep_together(elements):
335
+ """Wrap elements in KeepTogether only if their total height is reasonable.
336
+ If too tall, keep only the FIRST TWO elements together (e.g. title + table/image header)
337
+ to prevent title-content separation, while letting the rest paginate naturally.
338
+ """
339
+ total_h = 0
340
+ for el in elements:
341
+ w, h = el.wrap(A4[0] - 2*inch, A4[1])
342
+ total_h += h
343
+ if total_h <= MAX_KEEP_HEIGHT:
344
+ return [KeepTogether(elements)]
345
+ elif len(elements) >= 2:
346
+ # Keep at least title + first element together to prevent title orphaning
347
+ return [KeepTogether(elements[:2])] + list(elements[2:])
348
+ else:
349
+ return list(elements)
350
+
351
+ # Heading stays with first paragraph
352
+ story.extend(safe_keep_together([
353
+ heading_paragraph,
354
+ first_body_paragraph,
355
+ ]))
356
+
357
+ # Image + caption: keep together ONLY if image is small
358
+ story.extend(safe_keep_together([image, caption_paragraph]))
359
+
360
+ # Table title + table: keep together ONLY if table is short
361
+ if len(table_data) <= 15:
362
+ story.extend(safe_keep_together([table_title, table]))
363
+ else:
364
+ # Long table: just keep title with the table start
365
+ story.extend(safe_keep_together([table_title]))
366
+ story.append(table)
367
+ ```
368
+
369
+ **⚠️ KEY INSIGHT:** `KeepTogether` is the #1 cause of “empty page with chart on next page”.
370
+ When a `KeepTogether` block is taller than the remaining space on the current page,
371
+ ReportLab pushes the **entire block** to the next page, leaving the current page mostly empty.
372
+ **Always use `safe_keep_together()` to cap the maximum block height.**
373
+
374
+ **⚠️ Note:** Do NOT use `KeepWithNext` - it is unreliable in ReportLab 4.x.
375
+
376
+ ### Vertical Spacing Standards
377
+ * Before tables: `Spacer(1, 18)` after preceding text
378
+ * After tables: `Spacer(1, 6)` before table caption
379
+ * After table captions: `Spacer(1, 18)` before next content
380
+ * Between paragraphs: `Spacer(1, 12)` (~1 line)
381
+ * Between H3 subsections: `Spacer(1, 12)`
382
+ * Between H2 sections: `Spacer(1, 18)` (~1.5 lines)
383
+ * Between H1 sections: `Spacer(1, 24)` (~2 lines)
384
+ * NEVER use `Spacer(1, X)` where X > 24, except for H1 major breaks or cover page elements
385
+
386
+ ### Cover Page: HTML/Playwright Unified Cover System
387
+
388
+ **⚠️ Report route covers are ALWAYS generated via HTML/Playwright**, using the same 7-template system defined in `typesetting/cover.md`. This ensures visual consistency across all routes (Report, Creative, Academic) and avoids the limitations of ReportLab for complex cover layouts.
389
+
390
+ **Pipeline (Report route):**
391
+ 1. Generate **body PDF** via ReportLab (start with TOC or content - **no cover in story[]**)
392
+ 2. Generate **cover HTML** following `typesetting/cover.md` 7-template system
393
+ 3. **Run `poster_validate.py check-html` on cover HTML** — fix any ERRORs before rendering (overflow:hidden, font fallback, etc.)
394
+ 4. **Run `cover_validate.js` on cover HTML** — detects text-vs-decorative-line overlaps. Non-zero exit = must fix before proceeding.
395
+ ```bash
396
+ node "$PDF_SKILL_DIR/scripts/cover_validate.js" cover.html
397
+ ```
398
+ 5. Render cover HTML → single-page PDF via Playwright (`html2poster.js`) — **NOT `html2pdf-next.js`** (which converts absolute→static and destroys cover layout)
399
+ 6. **Merge: insert cover as page 0** of body PDF using pypdf → output single final PDF
400
+
401
+ > **Why not ReportLab covers?** ReportLab is excellent for structured content (tables, paragraphs, flowables) but painful for visual design (geometric accents, precise absolute positioning, web fonts). HTML/CSS handles these natively. One cover system, one visual standard, zero inconsistency.
402
+
403
+ **⚠️ Cover page is DEFAULT ON for all Report-route documents ≥ 3 pages.**
404
+
405
+ The Report route handles formal, structured documents. Readers expect a professional cover. **Always generate a cover unless the document type is explicitly excluded below.**
406
+
407
+ **ALWAYS add a cover page (default behavior):**
408
+ - Research reports, experiment reports, lab reports, analysis reports
409
+ - White papers, industry analysis, market research
410
+ - Business proposals, project plans, feasibility studies
411
+ - Technical documentation, product manuals, user guides
412
+ - Annual reports, financial summaries, quarterly reviews
413
+ - Any formal document ≥ 3 pages that will be shared externally or submitted
414
+
415
+ **NEVER add a cover page (explicit exclusions only):**
416
+ - **Resumes / CVs** - recruiters want content immediately
417
+ - **Letters / memos** - single-page or short-form
418
+ - **Forms / checklists / invoices** - functional documents
419
+ - **Internal notes / meeting minutes** - brevity over presentation
420
+ - **Documents ≤ 2 pages** - cover would be disproportionate
421
+ - **User explicitly said "no cover"**
422
+
423
+ **Rule of thumb:** If it's a report, analysis, proposal, or any formal document ≥ 3 pages → **add a cover**. When in doubt, add the cover. It's easier to remove a cover the user didn't want than to miss one they expected.
424
+
425
+ #### Step 1: Generate Body PDF (ReportLab, no cover)
426
+
427
+ Build the ReportLab document starting directly with TOC or first section. **Do NOT include any cover page in the `story[]` list.**
428
+
429
+ ```python
430
+ # Body PDF - starts with TOC or first section, NO cover
431
+ story = []
432
+ # story.append(toc) # if applicable
433
+ # story.append(PageBreak())
434
+ # story.append(first_section_content)
435
+ # ...
436
+ doc.build(story)
437
+ # Output: body.pdf (no cover)
438
+ ```
439
+
440
+ #### Step 2: Generate Cover PDF via html2poster.js
441
+
442
+ ```bash
443
+ # ALWAYS use html2poster.js for cover rendering (NOT html2pdf-next.js)
444
+ # Cover pages use position:absolute layout — html2pdf-next.js pre-render hooks
445
+ # convert absolute→static and destroy the layout. html2poster.js preserves it.
446
+ node "$PDF_SKILL_DIR/scripts/html2poster.js" cover.html --output cover.pdf --width 794px
447
+ ```
448
+
449
+ Or from Python:
450
+ ```python
451
+ import subprocess, os
452
+
453
+ def render_cover(html_path, pdf_path):
454
+ """Render HTML cover to PDF via html2poster.js.
455
+
456
+ ⚠️ ALWAYS use html2poster.js for covers (NOT html2pdf-next.js).
457
+ Cover HTML uses position:absolute for layout. html2pdf-next.js pre-render
458
+ hooks convert absolute→static to prevent multi-page overlap, which
459
+ destroys cover layouts. html2poster.js preserves absolute positioning.
460
+ """
461
+ scripts_dir = os.path.expanduser('~/.openclaw/workspace/skills/pdf/scripts')
462
+ subprocess.run([
463
+ 'node', os.path.join(scripts_dir, 'html2poster.js'),
464
+ html_path, '--output', pdf_path,
465
+ '--width', '794px',
466
+ ], check=True)
467
+ ```
468
+
469
+ **Insertion script (single output PDF):**
470
+ ```python
471
+ from pypdf import PdfReader, PdfWriter, Transformation
472
+
473
+ A4_W, A4_H = 595.28, 841.89 # A4 in points
474
+
475
+ def normalize_page_to_a4(page):
476
+ """Scale a page to A4 if its dimensions don't match."""
477
+ box = page.mediabox
478
+ w, h = float(box.width), float(box.height)
479
+ if abs(w - A4_W) > 2 or abs(h - A4_H) > 2:
480
+ sx, sy = A4_W / w, A4_H / h
481
+ page.add_transformation(Transformation().scale(sx=sx, sy=sy))
482
+ page.mediabox.lower_left = (0, 0)
483
+ page.mediabox.upper_right = (A4_W, A4_H)
484
+ return page
485
+
486
+ def insert_cover(cover_pdf, body_pdf, output_pdf):
487
+ """Insert cover as first page of body PDF → single output file."""
488
+ writer = PdfWriter()
489
+ # Cover as page 1
490
+ cover_page = PdfReader(cover_pdf).pages[0]
491
+ writer.add_page(normalize_page_to_a4(cover_page))
492
+ # Body pages follow
493
+ for page in PdfReader(body_pdf).pages:
494
+ writer.add_page(normalize_page_to_a4(page))
495
+ writer.add_metadata({'/Title': 'Report Title', '/Author': 'Z.ai', '/Creator': 'Z.ai'})
496
+ with open(output_pdf, 'wb') as f:
497
+ writer.write(f)
498
+ ```
499
+
500
+ > **⚠️ Size pitfall:** Playwright `page.pdf(width='794px', height='1123px')` output PDF dimensions may differ from A4 (595.28×841.89pt) by 1-2pt. **Do not use PIL Image.save('x.pdf')** for PNG→PDF conversion — DPI mapping causes severe size errors. You must call `normalize_page_to_a4()` to unify dimensions before insertion.
501
+
502
+ **Cover HTML template reference**: See `typesetting/cover.md` for the complete 7-Layout System with variants, typography scale, and bounding box rules.
503
+
504
+ **→ Full cover spec: `typesetting/cover.md`** - read it before designing any cover.
505
+
506
+ **Cover design rules (summary - see cover.md for details):**
507
+ - Page size: `width: 794px; height: 1123px` (A4 at 96dpi)
508
+ - `body { margin: 0; padding: 0; overflow: hidden; }` - REQUIRED to avoid white borders
509
+ - Load Google Fonts via `<link href="..." rel="stylesheet">` in `<head>` (NOT `@import url(...)` in CSS — `@import` must be first rule or is silently ignored) — Playwright fetches them at render time
510
+ - **Background must be white or very light** (`#fff` / `#fafafa` / `#f5f8fb`), no dark solid backgrounds or gradient backgrounds
511
+ - Primary color used only for text, lines, geometric accents - never as large-area background
512
+ - Sophistication = whitespace + typography + restrained geometric accents
513
+
514
+ **Cover Constitution (7-Layout System):**
515
+ - **Pick a layout (1-7)** from `typesetting/cover.md` that matches the document tone. No global default - every selection must be a deliberate design decision. Layout 7 for government/bidding/proposal documents.
516
+ - **Maximum 4 components** on any cover. Typical recipe: Title + subtitle + 1 geometric accent + metadata.
517
+ - **Typography Scale**: Title ≈ 45pt, Subtitle ≈ 25pt, Meta ≥ 18pt (never below 14pt). Tiny text = FAIL.
518
+ - **Background layer (optional)**: See `typesetting/cover-backgrounds.md` for 3 recipes (A=极简弧线, B=工程十字轴+立柱, C=锐角切割+出血文字). Background renders BELOW all foreground content at 2-5% opacity.
519
+ - **Mandatory `<br>` chunking**: Title MUST break every 2-4 words (CJK) or 3-5 words (English). Single-line title = FAIL.
520
+ - **Bounding Box spatial dispersion**: Group elements into 2-3 bounding boxes at opposite regions (e.g., top-left + bottom-right). Never cluster everything into middle 40%.
521
+ - **Safe Zone**: 12% top/bottom, 14% left/right padding on cover pages.
522
+ - **No body text on cover**: Cover = title + subtitle + date + optional geometric decoration. All content goes to page 2+.
523
+
524
+ ### ⚠️ Cover Page Isolation Rule (MANDATORY)
525
+
526
+ **The cover page must ALWAYS be on its own page.** Cover content and subsequent content (TOC, body text, etc.) must NEVER appear on the same page. This is a hard rule.
527
+
528
+ - **Report route (HTML/Playwright cover)**: The cover is a separate rendered page inserted as page 0 via pypdf - isolation is inherent in the merge pipeline
529
+ - **Creative route**: Cover is part of the same HTML document but on its own `<section>` with page-break - isolation is handled by CSS
530
+
531
+ If a generated PDF shows cover + TOC on the same page, it is a **critical bug** - regenerate immediately.
532
+
533
+ ### Alignment and Typography
534
+ - **CJK body**: Use `TA_LEFT` + 2-char indent. Headings: no indent.
535
+ - **Font sizes**: Body 11pt, subheadings 14pt, headings 18-20pt
536
+ - **Line height**: 1.5-1.6 (leading at **1.4x font size minimum**, recommended 1.5x for CJK)
537
+ - CJK characters are taller than Latin - 1.2x causes cramped lines
538
+ - Quick reference: 10pt→14pt min/18pt rec; 14pt→20pt min/22pt rec; 36pt→50pt min/54pt rec
539
+ - **⛔ Prohibited: fixed `rowHeights` in Table()**. Use `TOPPADDING` / `BOTTOMPADDING` to control row spacing. Fixed rowHeights cause content overflow clipping - the text renders but gets invisibly cut off.
540
+ - **CRITICAL: Alignment Selection Rule**:
541
+ - Use `TA_JUSTIFY` only when ALL of:
542
+ * Text is predominantly English (≥ 90%)
543
+ * Column width is sufficiently wide (A4 single-column body)
544
+ * Font: Western fonts (Times New Roman / Calibri)
545
+ * Chinese content: None or negligible
546
+ - Otherwise, always default to `TA_LEFT`
547
+ - For Chinese text, always add `wordWrap='CJK'` to ParagraphStyle
548
+
549
+ ### Style Configuration
550
+ * Normal paragraph: `spaceBefore=0`, `spaceAfter=6-12`
551
+ * Headings: `spaceBefore=12-18`, `spaceAfter=6-12`
552
+ * **Headings must be bold**: Use `<b></b>` tags in Paragraph
553
+ * Table captions: `spaceBefore=3`, `spaceAfter=6`, `alignment=TA_CENTER`
554
+ * **CRITICAL**: For Chinese text, always add `wordWrap='CJK'` to ParagraphStyle
555
+
556
+ ---
557
+
558
+ ## Table Formatting
559
+
560
+ ### Standard Table Color Scheme (MUST USE for ALL tables)
561
+
562
+ > **Colors MUST come from the palette generated in Step 2.** The values below are examples - replace them with your actual palette output.
563
+
564
+ ```python
565
+ # Colors from design_engine.py palette (Step 2) - NEVER hardcode these
566
+ TABLE_HEADER_COLOR = ACCENT # From palette --c-accent
567
+ TABLE_HEADER_TEXT = colors.white # White text for header (fixed)
568
+ TABLE_ROW_EVEN = colors.white # White for even rows
569
+ TABLE_ROW_ODD = BG_SURFACE # From palette --c-mid (light stripe)
570
+ ```
571
+
572
+ ### Table Rules
573
+ - Caption must be centered, added immediately after the table
574
+ - Entire table must be centered on the page
575
+ - **Header Row**: Dark background (from palette `header_fill`), white bold text
576
+ - **Cell Margins**: Left/Right at least 120-200 twips
577
+ - **Alignment**: Each body element within the same table must be aligned the same method
578
+ - **Color consistency**: All tables in one PDF must use the same color scheme
579
+ - **Spacing**: `Spacer(1, 18)` → Table → `Spacer(1, 6)` → Caption → `Spacer(1, 18)`
580
+
581
+ ### Table Centering Enforcement (MANDATORY)
582
+
583
+ **Every table MUST be horizontally centered on the page. No exceptions.**
584
+
585
+ ```python
586
+ # ReportLab: ALWAYS set hAlign='CENTER'
587
+ table = Table(data, colWidths=col_widths, hAlign='CENTER')
588
+
589
+ # Width rule: table total width should be 85-100% of available content width
590
+ available_width = doc.width # or page_width - left_margin - right_margin
591
+ table_width = sum(col_widths)
592
+ if table_width < available_width * 0.85:
593
+ # Scale up columns proportionally to fill space
594
+ scale = (available_width * 0.90) / table_width
595
+ col_widths = [w * scale for w in col_widths]
596
+
597
+ # ❌ WRONG — no hAlign (defaults to LEFT, table drifts left)
598
+ table = Table(data, colWidths=[100, 200, 150])
599
+
600
+ # ✅ RIGHT — explicit centering
601
+ table = Table(data, colWidths=[100, 200, 150], hAlign='CENTER')
602
+ ```
603
+
604
+ **LaTeX equivalent:**
605
+ ```latex
606
+ \begin{table}[htbp]
607
+ \centering % MANDATORY
608
+ \begin{tabular}{...}
609
+ ...
610
+ \end{tabular}
611
+ \end{table}
612
+ ```
613
+
614
+ ### Table Cell Content Rule (MANDATORY - NON-NEGOTIABLE)
615
+
616
+ **ALL text content in table cells MUST be wrapped in `Paragraph()`. NO EXCEPTIONS.**
617
+
618
+ ❌ **PROHIBITED** - Plain strings:
619
+ ```python
620
+ data = [
621
+ ['<b>Header</b>', 'Value'], # Bold won't render!
622
+ ['Pressure', '1.01 × 10<super>5</super>'], # Superscript won't work!
623
+ ]
624
+ ```
625
+
626
+ ✅ **REQUIRED** - All text in Paragraph:
627
+ ```python
628
+ data = [
629
+ [Paragraph('<b>Header</b>', header_style), Paragraph('Value', header_style)],
630
+ [Paragraph('Pressure', cell_style), Paragraph('1.01 × 10<super>5</super>', cell_style)],
631
+ ]
632
+ ```
633
+
634
+ **The ONLY exception**: `Image()` objects can be placed directly in table cells.
635
+
636
+ ### Units with Exponents (CRITICAL)
637
+ - PROHIBITED: `W/m2`, `kg/m3`, `m/s2` (plain text exponents)
638
+ - RIGHT: `Paragraph('W/m<super>2</super>', style)`, `Paragraph('kg/m<super>3</super>', style)`
639
+
640
+ ### Numeric Values in Tables (CRITICAL)
641
+ - Large numbers MUST use scientific notation: `Paragraph('-1.246 × 10<super>8</super>', style)` not `-124600000`
642
+ - Small decimals MUST use scientific notation: `Paragraph('2.5 × 10<super>-3</super>', style)` not `0.0025`
643
+ - Threshold: Use scientific notation when |value| ≥ 10000 or |value| ≤ 0.001
644
+
645
+ ### Complete Table Example
646
+ ```python
647
+ from reportlab.platypus import Table, TableStyle, Paragraph, Image
648
+ from reportlab.lib.styles import ParagraphStyle
649
+ from reportlab.lib import colors
650
+ from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
651
+
652
+ header_style = ParagraphStyle(
653
+ name='TableHeader', fontName='Times New Roman', fontSize=11,
654
+ textColor=colors.white, alignment=TA_CENTER
655
+ )
656
+ cell_style = ParagraphStyle(
657
+ name='TableCell', fontName='Times New Roman', fontSize=10,
658
+ textColor=colors.black, alignment=TA_CENTER
659
+ )
660
+
661
+ data = [
662
+ [Paragraph('<b>Parameter</b>', header_style),
663
+ Paragraph('<b>Unit</b>', header_style),
664
+ Paragraph('<b>Value</b>', header_style)],
665
+ [Paragraph('Temperature', cell_style),
666
+ Paragraph('°C', cell_style),
667
+ Paragraph('25.5', cell_style)],
668
+ [Paragraph('Pressure', cell_style),
669
+ Paragraph('Pa', cell_style),
670
+ Paragraph('1.01 × 10<super>5</super>', cell_style)],
671
+ [Paragraph('Density', cell_style),
672
+ Paragraph('kg/m<super>3</super>', cell_style),
673
+ Paragraph('1.225', cell_style)],
674
+ ]
675
+
676
+ table = Table(data, colWidths=[120, 80, 100])
677
+ # ⚠️ Above uses hardcoded widths - OK for this 3-col example (120+80+100=300 < available ~460pt).
678
+ # For real tables, ALWAYS calculate from available_width. See "Table Width Management" below.
679
+ table.setStyle(TableStyle([
680
+ ('BACKGROUND', (0, 0), (-1, 0), ACCENT), # Header: palette accent
681
+ ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
682
+ ('BACKGROUND', (0, 1), (-1, 1), colors.white),
683
+ ('BACKGROUND', (0, 2), (-1, 2), BG_SURFACE), # Odd row: palette surface
684
+ ('BACKGROUND', (0, 3), (-1, 3), colors.white),
685
+ ('GRID', (0, 0), (-1, -1), 0.5, TEXT_MUTED), # Grid: palette muted
686
+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
687
+ ('LEFTPADDING', (0, 0), (-1, -1), 8),
688
+ ('RIGHTPADDING', (0, 0), (-1, -1), 8),
689
+ ('TOPPADDING', (0, 0), (-1, -1), 6),
690
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
691
+ ]))
692
+ ```
693
+
694
+ ### Table Width Management (⚠️ Prevent Table Overflow)
695
+
696
+ **Most common table bug: columns overflow the right page margin because colWidths are hardcoded without checking available space.**
697
+
698
+ **Iron Rule: The sum of all colWidths MUST NOT exceed `available_width`.**
699
+
700
+ ```python
701
+ from reportlab.lib.pagesizes import A4
702
+ from reportlab.lib.units import inch
703
+
704
+ page_width = A4[0] # 595.28pt
705
+ left_margin = 1.0 * inch # 72pt (adjust to your doc's actual margins)
706
+ right_margin = 1.0 * inch # 72pt
707
+ available_width = page_width - left_margin - right_margin # ≈ 451pt
708
+
709
+ # ─── Method 1: Proportional widths (RECOMMENDED) ───
710
+ # Define column ratios, auto-scale to fit available_width
711
+ col_ratios = [0.25, 0.40, 0.20, 0.15] # must sum to 1.0
712
+ col_widths = [r * available_width for r in col_ratios]
713
+ table = Table(data, colWidths=col_widths)
714
+
715
+ # ─── Method 2: Fixed + flex columns ───
716
+ # Some columns have fixed width (numbers, dates), rest fills remaining space
717
+ fixed_cols = {0: 80, 3: 60} # col 0 = 80pt, col 3 = 60pt
718
+ fixed_total = sum(fixed_cols.values())
719
+ flex_count = 4 - len(fixed_cols) # total columns minus fixed
720
+ flex_width = (available_width - fixed_total) / flex_count
721
+ col_widths = []
722
+ for i in range(4):
723
+ col_widths.append(fixed_cols.get(i, flex_width))
724
+ table = Table(data, colWidths=col_widths)
725
+
726
+ # ─── Method 3: Let ReportLab auto-calculate (simplest, less control) ───
727
+ # Pass colWidths=None - ReportLab auto-sizes based on content
728
+ # ⚠️ Risk: may still overflow if content is too wide
729
+ table = Table(data) # no colWidths
730
+ ```
731
+
732
+ **Checklist before adding any table:**
733
+ 1. Calculate `available_width` from your actual page size and margins
734
+ 2. Sum all colWidths - must be ≤ `available_width`
735
+ 3. For CJK text: characters are wider than Latin - budget ~12pt per CJK char at 10pt font
736
+ 4. If a column has long text (descriptions, policies), use Paragraph() wrapping inside cells (not plain strings) - plain strings don't wrap and will overflow
737
+ 5. Test with the longest expected content in each column
738
+
739
+ **Common mistake - plain strings don't wrap:**
740
+ ```python
741
+ # ❌ Plain string: will overflow if text is long
742
+ data = [['Policy Name', 'Very long description that keeps going and going']]
743
+ # ✅ Paragraph: wraps within column width
744
+ from reportlab.platypus import Paragraph
745
+ from reportlab.lib.styles import getSampleStyleSheet
746
+ styles = getSampleStyleSheet()
747
+ cell_style = styles['Normal']
748
+ data = [[Paragraph('Policy Name', cell_style),
749
+ Paragraph('Very long description that keeps going and going', cell_style)]]
750
+ ```
751
+
752
+ ```
753
+ Do you need auto-TOC?
754
+ ├─ YES → Use TocDocTemplate + doc.multiBuild(story)
755
+ └─ NO → Use SimpleDocTemplate + doc.build(story)
756
+ ```
757
+
758
+ | Requirement | DocTemplate | Build Method |
759
+ |-------------|-------------|--------------|
760
+ | Multi-page with TOC | `TocDocTemplate` | `multiBuild()` |
761
+ | Single-page or no TOC | `SimpleDocTemplate` | `build()` |
762
+ | With Cross-References (no TOC) | `SimpleDocTemplate` | `build()` |
763
+ | Both TOC + Cross-References | `TocDocTemplate` | `multiBuild()` |
764
+
765
+ **⚠️ CRITICAL**:
766
+ - `multiBuild()` is ONLY needed when using `TableOfContents`
767
+ - Using `build()` with `TocDocTemplate` = TOC won't work
768
+ - Using `multiBuild()` without `TocDocTemplate` = unnecessary overhead
769
+
770
+ ---
771
+
772
+ ## Rich Text Formatting
773
+
774
+ ### Prerequisites
775
+ To use `<b>`, `<super>`, `<sub>` tags, you **must**:
776
+ 1. Register fonts via `registerFont()`
777
+ 2. Call `registerFontFamily()` to link normal/bold/italic variants
778
+ 3. Wrap all tagged text in `Paragraph()` objects
779
+
780
+ **CRITICAL**: These tags ONLY work inside `Paragraph()` objects. Plain strings will NOT render them.
781
+
782
+ ### Preventing Unwanted Line Breaks
783
+
784
+ ```python
785
+ # Use non-breaking space to prevent breaking
786
+ text = Paragraph("Professors (K.G.\u00A0Palepu) proposed...", style)
787
+
788
+ # Use wordWrap='CJK' for proper Chinese typography
789
+ styles.add(ParagraphStyle(name='BodyStyle', fontName='SimHei', fontSize=10.5,
790
+ leading=18, alignment=TA_LEFT, wordWrap='CJK'))
791
+
792
+ # Use <br/> for intentional line breaks (NOT \n)
793
+ text = Paragraph("Line 1<br/>Line 2<br/>Line 3", style)
794
+ ```
795
+
796
+ ---
797
+
798
+ ## Auto-Generated Table of Contents
799
+
800
+ ### ❌ FORBIDDEN: Manual Table of Contents
801
+ **NEVER manually create TOC with hardcoded page numbers.**
802
+
803
+ ### ⚠️ MANDATORY: TOC requires a cover page
804
+ **Unless the user explicitly requests no cover, if a document has a Table of Contents, it MUST have a cover page.** Structure: Cover (page 1) → TOC (page 2) → Content (page 3+). Do not generate a TOC without a preceding cover page.
805
+
806
+ ### ✅ ALWAYS use auto-generated TOC:
807
+
808
+ ```python
809
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak, Spacer
810
+ from reportlab.platypus.tableofcontents import TableOfContents
811
+ from reportlab.lib.utils import simpleSplit
812
+ import hashlib
813
+
814
+ class TocDocTemplate(SimpleDocTemplate):
815
+ def afterFlowable(self, flowable):
816
+ if hasattr(flowable, 'bookmark_name'):
817
+ level = getattr(flowable, 'bookmark_level', 0)
818
+ text = getattr(flowable, 'bookmark_text', '')
819
+ key = getattr(flowable, 'bookmark_key', '')
820
+ # MUST pass key as 4th element - without it, TOC entries won't have clickable links
821
+ self.notify('TOCEntry', (level, text, self.page, key))
822
+
823
+ doc = TocDocTemplate("document.pdf", pagesize=letter)
824
+ story = []
825
+
826
+ toc = TableOfContents()
827
+ toc.levelStyles = [
828
+ ParagraphStyle(name='TOCHeading1', fontSize=14, leftIndent=20, fontName='Times New Roman'),
829
+ ParagraphStyle(name='TOCHeading2', fontSize=12, leftIndent=40, fontName='Times New Roman'),
830
+ ]
831
+ story.append(Paragraph("<b>Table of Contents</b>", styles['Title']))
832
+ story.append(toc)
833
+ story.append(PageBreak())
834
+
835
+ def add_heading(text, style, level=0):
836
+ # Generate a unique bookmark key for this heading
837
+ key = 'h_%s' % hashlib.md5(text.encode()).hexdigest()[:8]
838
+ p = Paragraph('<a name="%s"/>%s' % (key, text), style)
839
+ p.bookmark_name = text
840
+ p.bookmark_level = level
841
+ p.bookmark_text = text
842
+ p.bookmark_key = key # This key enables clickable TOC links
843
+ return p
844
+
845
+ # ⚠️ Orphan Heading Prevention (NOT a page break rule)
846
+ # If an H1 heading would appear in the bottom 15% of the page with no room
847
+ # for at least a few lines of content, push it to the next page.
848
+ # This is NOT "every H1 starts a new page" — it only triggers when the heading
849
+ # would be orphaned at the very bottom.
850
+ available_height = A4[1] - top_margin - bottom_margin
851
+ H1_ORPHAN_THRESHOLD = available_height * 0.15 # ~100pt ≈ 3.5cm — enough for heading + 2 lines
852
+
853
+ def add_major_section(text, style):
854
+ """Add an H1-level heading with orphan prevention (NOT forced page break)."""
855
+ return [
856
+ CondPageBreak(H1_ORPHAN_THRESHOLD), # Only break if heading would be orphaned at page bottom
857
+ add_heading(text, style, level=0),
858
+ ]
859
+
860
+ story.extend(add_major_section("Chapter 1: Introduction", styles['Heading1']))
861
+ # ... content ...
862
+
863
+ doc.multiBuild(story) # MUST use multiBuild for TOC
864
+ ```
865
+
866
+ **⚠️ CRITICAL TOC LINK RULES:**
867
+ 1. `afterFlowable` MUST pass `key` as the 4th element in the notify tuple - without it, TOC entries have no clickable links
868
+ 2. `add_heading` MUST set `bookmark_key` AND embed `<a name="key"/>` in the Paragraph text - this creates the link destination
869
+ 3. The key must be unique per heading - use a hash of the heading text
870
+
871
+ ### TOC with Leader Dots (Copy-Paste Ready)
872
+
873
+ **⚠️ WARNING**: This manual approach creates a visual-only TOC. It has **NO clickable links** and **NO auto-updated page numbers**. Use the auto-generated TOC above (TocDocTemplate + multiBuild) whenever possible. Only use this leader-dots approach if you need very specific visual styling that the auto TOC cannot provide - and even then, prefer the auto approach.
874
+
875
+ For a professional TOC with leader dots connecting titles to page numbers:
876
+
877
+ ```python
878
+ from reportlab.lib.pagesizes import A4
879
+ from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, PageBreak
880
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
881
+ from reportlab.lib import colors
882
+ from reportlab.lib.units import inch
883
+
884
+ # Setup
885
+ doc = SimpleDocTemplate("report.pdf", pagesize=A4,
886
+ leftMargin=0.75*inch, rightMargin=0.75*inch)
887
+ styles = getSampleStyleSheet()
888
+ styles['Heading1'].fontName = 'Times New Roman'
889
+ styles['Heading1'].textColor = colors.black
890
+
891
+ story = []
892
+
893
+ # Calculate dimensions
894
+ page_width = A4[0]
895
+ available_width = page_width - 1.5*inch
896
+ page_num_width = 50 # Fixed width for page numbers
897
+ dots_column_width = available_width - 200 - page_num_width
898
+ optimal_dot_count = int(dots_column_width / 4.5) # ~4.5pt per dot at 7pt font
899
+
900
+ # Define styles
901
+ toc_style = ParagraphStyle('TOCEntry', parent=styles['Normal'],
902
+ fontName='Times New Roman', fontSize=11, leading=16)
903
+ dots_style = ParagraphStyle('LeaderDots', parent=styles['Normal'],
904
+ fontName='Times New Roman', fontSize=7, leading=16)
905
+
906
+ # Build TOC
907
+ toc_data = [
908
+ [Paragraph('<b>Table of Contents</b>', styles['Heading1']), '', ''],
909
+ ['', '', ''],
910
+ ]
911
+
912
+ entries = [('Section 1', '5'), ('Section 2', '10')]
913
+ for title, page in entries:
914
+ toc_data.append([
915
+ Paragraph(title, toc_style),
916
+ Paragraph('.' * optimal_dot_count, dots_style),
917
+ Paragraph(page, toc_style)
918
+ ])
919
+
920
+ toc_table = Table(toc_data, colWidths=[None, dots_column_width, page_num_width])
921
+ toc_table.setStyle(TableStyle([
922
+ ('GRID', (0, 0), (-1, -1), 0, colors.white),
923
+ ('LINEBELOW', (0, 0), (0, 0), 1.5, colors.black),
924
+ ('ALIGN', (0, 0), (0, -1), 'LEFT'),
925
+ ('ALIGN', (1, 0), (1, -1), 'LEFT'),
926
+ ('ALIGN', (2, 0), (2, -1), 'RIGHT'),
927
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
928
+ ('LEFTPADDING', (0, 0), (-1, -1), 0),
929
+ ('RIGHTPADDING', (0, 0), (-1, -1), 0),
930
+ ('TOPPADDING', (0, 2), (-1, -1), 3),
931
+ ('BOTTOMPADDING', (0, 2), (-1, -1), 3),
932
+ ('TEXTCOLOR', (1, 2), (1, -1), TEXT_MUTED), # From palette --c-muted
933
+ ]))
934
+
935
+ story.append(toc_table)
936
+ story.append(PageBreak())
937
+ doc.build(story)
938
+ ```
939
+
940
+ **MANDATORY Leader Dots Rules:**
941
+
942
+ | Rule | Requirement |
943
+ |------|-------------|
944
+ | Column widths | ✅ MUST use fixed values. Percentage-based widths are **STRICTLY FORBIDDEN**. |
945
+ | Dot count | ✅ MUST calculate dynamically: `int(dots_column_width / 4.5)`. Hard-coded counts are **STRICTLY FORBIDDEN**. |
946
+ | Page number column | ✅ MUST be at least 40pt wide. |
947
+ | Dot font size | ✅ MUST NOT exceed 8pt. |
948
+ | Dot alignment | ✅ MUST be LEFT-aligned (visual flow from title). |
949
+ | Padding | ✅ MUST be exactly 0 between columns. |
950
+ | Bold text | ✅ MUST use `Paragraph('<b>Text</b>', style)`. Plain strings like `'<b>Text</b>'` are **STRICTLY FORBIDDEN**. |
951
+ | Indentation | Use leading spaces for hierarchy (e.g., `" 1.1 Subsection"`). |
952
+
953
+ ### TOC Post-Generation Validation (MANDATORY)
954
+
955
+ After generating any PDF with a Table of Contents, run:
956
+
957
+ ```bash
958
+ python3 "$PDF_SKILL_DIR/scripts/toc_validate.py" check-pdf output.pdf
959
+ ```
960
+
961
+ If any errors are returned, fix the code and regenerate. Common issues:
962
+ - `TOC_ALL_SAME_PAGE` → You used `build()` instead of `multiBuild()`, so all page numbers are stuck at 1.
963
+ - `TOC_NO_ENTRIES` → Headings are missing `bookmark_name`/`bookmark_level` attributes.
964
+ - `TOC_PAGES_INVALID` → A TOC entry references a page beyond the document's total page count.
965
+
966
+ ---
967
+
968
+ ## Cross-References (Figures, Tables, Bibliography)
969
+
970
+ Pre-register all figures, tables, and references BEFORE using them in text.
971
+
972
+ ```python
973
+ class CrossReferenceDocument:
974
+ def __init__(self):
975
+ self.figures = {}
976
+ self.tables = {}
977
+ self.refs = {}
978
+ self.figure_counter = 0
979
+ self.table_counter = 0
980
+ self.ref_counter = 0
981
+
982
+ def add_figure(self, name):
983
+ if name not in self.figures:
984
+ self.figure_counter += 1
985
+ self.figures[name] = self.figure_counter
986
+ return self.figures[name]
987
+
988
+ def add_table(self, name):
989
+ if name not in self.tables:
990
+ self.table_counter += 1
991
+ self.tables[name] = self.table_counter
992
+ return self.tables[name]
993
+
994
+ def add_reference(self, name):
995
+ if name not in self.refs:
996
+ self.ref_counter += 1
997
+ self.refs[name] = self.ref_counter
998
+ return self.refs[name]
999
+ ```
1000
+
1001
+ ---
1002
+
1003
+ ## Image Handling
1004
+
1005
+ ### Diagram Embedding Rules (MANDATORY)
1006
+
1007
+ **Figures are block-level Flowables.** Every image/diagram in ReportLab MUST be appended to `story` as a standalone `Image()` or wrapped in `KeepTogether([image, caption])`. Never simulate floating layouts by placing images inside Paragraph text or multi-column Table cells alongside body text.
1008
+
1009
+ **Complex diagrams (>12 nodes)**: Decompose into a ReportLab Table (details) + a simplified diagram image (overview). The diagram gives the big picture; the table carries precision. See SKILL.md "Complex Diagram Strategy".
1010
+
1011
+ **Diagram quality**: When generating flowcharts/diagrams for PDF embedding (via Playwright screenshot or ReportLab Drawing), follow the diagram content quality rules in SKILL.md § "Diagram Content Quality Rules". Key points: connectors must not pass through nodes, no high-saturation large fills, multi-arrow convergence must use merge pattern, font sizes must be legible at final embedded size (see context-specific minimums in SKILL.md).
1012
+
1013
+ **Cross-brief diagram pipeline**: For flowcharts/architecture diagrams, generate via **Playwright+CSS** (HTML nodes + CSS layout + SVG connectors), screenshot at 2× device scale factor for 300dpi print quality, then embed with `Image()`. See SKILL.md § "Diagram Generation Strategy" for the full pipeline.
1014
+
1015
+ **🚫 FORBIDDEN: TikZ standalone → PNG pipeline in Report brief.** Report uses ReportLab, not LaTeX. Going through TikZ requires a LaTeX compiler, adds compilation steps, and models frequently produce broken TikZ code. Use Playwright+CSS instead - it's native to the existing cover rendering engine.
1016
+
1017
+ ```python
1018
+ # Playwright+CSS diagram → PNG → ReportLab embedding
1019
+ # 1. LLM generates diagram.html (CSS grid/flexbox nodes + SVG arrows)
1020
+ # 2. Playwright screenshots at 2× scale (300dpi equivalent)
1021
+ # 3. Embed:
1022
+ from reportlab.platypus import Image
1023
+ img = Image('diagram.png', width=450) # auto height via aspect ratio
1024
+ story.append(img) # block-level Flowable
1025
+ ```
1026
+
1027
+ **⚠️ CRITICAL: Preserve aspect ratio - NEVER hardcode both width and height without reading actual image dimensions.**
1028
+
1029
+ **⚠️ CRITICAL: Always constrain to available space - NEVER insert at original size if it exceeds container width/height.**
1030
+
1031
+ Pie charts become ellipses, radar charts become diamonds, photos get stretched if you set arbitrary width/height.
1032
+
1033
+ **→ Full overflow prevention spec: `typesetting/overflow.md`** - read for the complete bounding box system.
1034
+
1035
+ ```python
1036
+ from PIL import Image as PILImage
1037
+ from reportlab.platypus import Image
1038
+ from reportlab.lib.pagesizes import A4
1039
+ from reportlab.lib.units import inch
1040
+
1041
+ def embed_image(path: str, max_width: float = None, max_height: float = None) -> Image:
1042
+ """Embed image with preserved aspect ratio, constrained to container.
1043
+
1044
+ ALWAYS use this pattern. Never hardcode both width and height.
1045
+ If max_width is None, defaults to available_width (page - margins).
1046
+ """
1047
+ if max_width is None:
1048
+ max_width = A4[0] - 2.0 * inch # Default: A4 width minus 1" margins each side
1049
+ if max_height is None:
1050
+ max_height = A4[1] * 0.35 # ~294pt ≈ 10cm — leaves room for caption + surrounding text on same page
1051
+
1052
+ pil_img = PILImage.open(path)
1053
+ orig_w, orig_h = pil_img.size
1054
+
1055
+ # Scale to fit within BOTH max_width and max_height
1056
+ ratio_w = max_width / orig_w if orig_w > max_width else 1.0
1057
+ ratio_h = max_height / orig_h if orig_h > max_height else 1.0
1058
+ ratio = min(ratio_w, ratio_h)
1059
+
1060
+ return Image(path, width=orig_w * ratio, height=orig_h * ratio)
1061
+
1062
+ # Usage:
1063
+ available_width = A4[0] - left_margin - right_margin
1064
+ img = embed_image('chart.png', max_width=available_width, max_height=300)
1065
+ story.append(img)
1066
+ ```
1067
+
1068
+ ```python
1069
+ # ❌ NEVER do this - distorts the image:
1070
+ img = Image('chart.png', width=400, height=250) # arbitrary height breaks aspect ratio
1071
+ ```
1072
+
1073
+ ---
1074
+
1075
+ ## PDF Metadata
1076
+
1077
+ ```python
1078
+ doc = SimpleDocTemplate(
1079
+ pdf_filename,
1080
+ pagesize=letter,
1081
+ title=os.path.splitext(pdf_filename)[0],
1082
+ author='Z.ai',
1083
+ creator='Z.ai',
1084
+ subject='Document purpose description'
1085
+ )
1086
+ ```
1087
+
1088
+ ### ⚠️ MANDATORY: Post-Generation Metadata
1089
+
1090
+ After `doc.build(story)` completes:
1091
+ ```bash
1092
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" meta.brand output.pdf
1093
+ ```
1094
+
1095
+ ### ⚠️ MANDATORY: Post-Generation Blank Page Cleanup
1096
+
1097
+ After metadata branding, remove any accidental blank pages:
1098
+ ```bash
1099
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" pages.clean output.pdf -o output_clean.pdf
1100
+ ```
1101
+ If blank pages were found, rename `output_clean.pdf` → `output.pdf`.
1102
+
1103
+ ---
1104
+
1105
+ ## MANDATORY: Post-Generation Code Sanitization
1106
+
1107
+ **After writing PDF generation code and BEFORE executing it**, sanitize using:
1108
+
1109
+ ```bash
1110
+ # Step 0: Set skill root path (see SKILL.md § Script Path Setup)
1111
+ PDF_SKILL_DIR="<skill_directory>"
1112
+
1113
+ # Step 1: Write code to .py file
1114
+ cat > generate_pdf.py << 'PYEOF'
1115
+ # ... your PDF generation code ...
1116
+ PYEOF
1117
+
1118
+ # Step 2: Sanitize (MUST run before execution)
1119
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" code.sanitize generate_pdf.py
1120
+
1121
+ # Step 3: Execute
1122
+ python3 generate_pdf.py
1123
+
1124
+ # Step 4: Add metadata (MUST run after PDF creation)
1125
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" meta.brand output.pdf
1126
+
1127
+ # Step 5: Check for missing glyphs (RECOMMENDED)
1128
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" font.check output.pdf
1129
+
1130
+ # Step 6: Check TOC quality (if document has TOC)
1131
+ python3 "$PDF_SKILL_DIR/scripts/pdf.py" toc.check output.pdf
1132
+
1133
+ # Step 7: PDF quality assurance scan (MUST run after all other checks)
1134
+ python3 "$PDF_SKILL_DIR/scripts/pdf_qa.py" output.pdf
1135
+ ```
1136
+
1137
+ **FORBIDDEN patterns:**
1138
+ ```bash
1139
+ # ❌ PROHIBITED: python -c with inline code
1140
+ python -c "from reportlab... doc.build(story)"
1141
+
1142
+ # ❌ PROHIBITED: heredoc without saving to file first
1143
+ python3 << 'EOF'
1144
+ from reportlab...
1145
+ EOF
1146
+
1147
+ # ❌ PROHIBITED: executing .py without sanitizing
1148
+ python generate_pdf.py # Missing sanitization!
1149
+ ```
1150
+
1151
+ ---
1152
+
1153
+ ## Debug Tips for Layout Issues
1154
+
1155
+ **→ Full overflow prevention spec: `typesetting/overflow.md`** - read it for the complete bounding box system, two-pass rendering, fallback strategies, and all three route implementations.
1156
+
1157
+ ```python
1158
+ from reportlab.platypus import HRFlowable
1159
+ from reportlab.lib.colors import red
1160
+
1161
+ # Visualize spacing during development - insert between elements
1162
+ story.append(table)
1163
+ story.append(HRFlowable(width="100%", color=red, thickness=0.5, spaceBefore=0, spaceAfter=0))
1164
+ story.append(Spacer(1, 6))
1165
+ story.append(HRFlowable(width="100%", color=red, thickness=0.5, spaceBefore=0, spaceAfter=0))
1166
+ story.append(caption)
1167
+ # Red lines create visual markers to see actual spacing - remove before final build
1168
+ ```
1169
+
1170
+ ---
1171
+
1172
+ ## Resume / CV Template (ATS-Friendly)
1173
+
1174
+ Single-column, clean layout optimised for Applicant Tracking Systems (ATS). No graphics, no sidebars, no colour blocks - just well-structured text that parses perfectly by HR software.
1175
+
1176
+ **When to use this template:**
1177
+ - Applying to corporate jobs through online portals
1178
+ - Any scenario where the PDF will be machine-parsed before a human reads it
1179
+ - When the recruiter explicitly asks for "a standard resume"
1180
+
1181
+ **When NOT to use (use Academic brief instead):**
1182
+ - Creative/design industry positions → Academic brief (AltaCV-style)
1183
+ - Academic CV with publications → Academic brief (Academic CV)
1184
+
1185
+ ### Resume Design Rules
1186
+ - **Target 1 page** unless user specifies otherwise
1187
+ - **Margins**: `left=1.5cm, right=1.5cm, top=1.5cm, bottom=1.5cm`
1188
+ - **No cover page** - content starts immediately
1189
+ - **No TOC** - too short for table of contents
1190
+ - **Font**: Times New Roman (English) or SimHei (Chinese)
1191
+ - **Body font size**: 10-10.5pt; Name: 22-26pt; Section titles: 13-14pt
1192
+ - **⚠️ Minimum font size: 12px (9pt) - HARD FLOOR.** No text in the entire resume may render smaller than 12px. This includes contact info, meta text, footnotes, and captions. Anything below 12px is unreadable in print and fails accessibility checks.
1193
+ - **Section separator**: thin horizontal rule (`HRFlowable`)
1194
+ - **Bullet style**: `•` with tight spacing
1195
+
1196
+ ### Resume Line-Break Rules (Language-Aware)
1197
+ - **English**: Prefer breaking at word boundaries (spaces, hyphens). If a long word must be split to avoid excessive whitespace, break at a valid syllable boundary and insert a hyphen (`-`) - this is standard typographic practice (e.g., `experi-\nence`, `develop-\nment`). ReportLab supports `wordWrap='CJK'` only for CJK content; for English use default paragraph wrapping with `allowWidows=0, allowOrphans=0`.
1198
+ - **Chinese/CJK**: Break allowed between any two CJK characters. Never break between a CJK character and its adjacent punctuation (、。,)》 etc. must stay with the preceding character).
1199
+ - **Mixed content** (e.g., "Python 开发工程师"): Break at CJK boundaries or English word boundaries. Never split an English word in a CJK paragraph unless hyphenated.
1200
+ - **Contact line**: Email, phone, location separated by `|` or `·`. Each segment must stay on one line - if too long, move to next line at the separator, not mid-segment.
1201
+ - **Dates and ranges**: "Jan 2022 - Present" must stay as one unit. Never break a date range across lines.
1202
+
1203
+ ### Resume Page-Fill Rules (Anti-Blank-Space)
1204
+ - **Goal: Fill ≥85% of the page height.** Content should reach at least the bottom quarter of the page. A resume that stops at 60% height with blank space below = FAIL.
1205
+ - **Adaptive spacing strategy** (apply in order until page is ≥85% filled):
1206
+ 1. Increase `spaceBefore` / `spaceAfter` on section headers (from 10pt up to 18pt)
1207
+ 2. Increase `leading` (line height) on body text (from 14pt up to 18pt)
1208
+ 3. Increase body `fontSize` by 0.5-1pt (from 10pt up to 11.5pt max)
1209
+ 4. Add a "Professional Summary" or "Key Achievements" section if none exists
1210
+ 5. Increase margins slightly (from 1.5cm up to 2cm) to reduce line width and push content downward
1211
+ - **Never leave a visible blank area > 3cm at the bottom of the page.**
1212
+ - **If content overflows to page 2**: do the reverse - reduce spacing, tighten leading (min 12pt), reduce fontSize (min 9pt / 12px), before removing content.
1213
+
1214
+ ### Complete Resume Template
1215
+
1216
+ ```python
1217
+ from reportlab.lib.pagesizes import A4
1218
+ from reportlab.lib.units import cm, mm
1219
+ from reportlab.lib.styles import ParagraphStyle
1220
+ from reportlab.lib.enums import TA_LEFT, TA_CENTER
1221
+ from reportlab.lib import colors
1222
+ from reportlab.platypus import (
1223
+ SimpleDocTemplate, Paragraph, Spacer, HRFlowable, Table, TableStyle
1224
+ )
1225
+ from reportlab.pdfbase import pdfmetrics
1226
+ from reportlab.pdfbase.ttfonts import TTFont
1227
+ from reportlab.pdfbase.pdfmetrics import registerFontFamily
1228
+
1229
+ # ── Font Registration ──
1230
+ pdfmetrics.registerFont(TTFont('TimesNewRoman', '/usr/share/fonts/truetype/english/Times-New-Roman.ttf'))
1231
+ registerFontFamily('TimesNewRoman', normal='TimesNewRoman', bold='TimesNewRoman')
1232
+ # For Chinese resumes, also register SimHei:
1233
+ # pdfmetrics.registerFont(TTFont('SimHei', '/usr/share/fonts/truetype/chinese/SimHei.ttf'))
1234
+ # registerFontFamily('SimHei', normal='SimHei', bold='SimHei')
1235
+
1236
+ # ── Styles ──
1237
+ # ACCENT must come from palette.generate (Step 2)
1238
+ # Run: python3 "$PDF_SKILL_DIR/scripts/pdf.py" palette.generate --title "Resume" --mode minimal
1239
+ ACCENT = colors.HexColor('<accent from palette>') # Replace with palette output
1240
+
1241
+ name_style = ParagraphStyle(
1242
+ 'ResumeName', fontName='TimesNewRoman', fontSize=24,
1243
+ leading=28, alignment=TA_CENTER, spaceAfter=2
1244
+ )
1245
+ contact_style = ParagraphStyle(
1246
+ 'ResumeContact', fontName='TimesNewRoman', fontSize=10,
1247
+ leading=14, alignment=TA_CENTER, textColor=TEXT_MUTED, # From palette --c-muted
1248
+ spaceAfter=8
1249
+ )
1250
+ section_title_style = ParagraphStyle(
1251
+ 'ResumeSectionTitle', fontName='TimesNewRoman', fontSize=13,
1252
+ leading=16, spaceBefore=10, spaceAfter=4,
1253
+ textColor=ACCENT
1254
+ )
1255
+ job_title_style = ParagraphStyle(
1256
+ 'ResumeJobTitle', fontName='TimesNewRoman', fontSize=11,
1257
+ leading=14, spaceAfter=1
1258
+ )
1259
+ job_meta_style = ParagraphStyle(
1260
+ 'ResumeJobMeta', fontName='TimesNewRoman', fontSize=10,
1261
+ leading=13, textColor=TEXT_MUTED, spaceAfter=4 # From palette --c-muted
1262
+ )
1263
+ bullet_style = ParagraphStyle(
1264
+ 'ResumeBullet', fontName='TimesNewRoman', fontSize=10,
1265
+ leading=14, leftIndent=14, bulletIndent=0,
1266
+ spaceBefore=1, spaceAfter=1
1267
+ )
1268
+ body_style = ParagraphStyle(
1269
+ 'ResumeBody', fontName='TimesNewRoman', fontSize=10,
1270
+ leading=14, spaceAfter=2
1271
+ )
1272
+
1273
+ # ── Helpers ──
1274
+ def section_header(title):
1275
+ """Section title + thin rule separator."""
1276
+ return [
1277
+ Paragraph(f'<b>{title}</b>', section_title_style),
1278
+ HRFlowable(width='100%', thickness=0.8, color=ACCENT,
1279
+ spaceBefore=0, spaceAfter=6),
1280
+ ]
1281
+
1282
+ def experience_entry(title, company, dates, location, bullets):
1283
+ """One work experience block."""
1284
+ elements = [
1285
+ Paragraph(f'<b>{title}</b>', job_title_style),
1286
+ Paragraph(f'{company} | {dates} | {location}', job_meta_style),
1287
+ ]
1288
+ for b in bullets:
1289
+ elements.append(Paragraph(f'• {b}', bullet_style))
1290
+ elements.append(Spacer(1, 4))
1291
+ return elements
1292
+
1293
+ def education_entry(degree, school, dates, details=None):
1294
+ """One education block."""
1295
+ elements = [
1296
+ Paragraph(f'<b>{degree}</b>', job_title_style),
1297
+ Paragraph(f'{school} | {dates}', job_meta_style),
1298
+ ]
1299
+ if details:
1300
+ elements.append(Paragraph(details, body_style))
1301
+ elements.append(Spacer(1, 4))
1302
+ return elements
1303
+
1304
+ def skills_row(categories):
1305
+ """
1306
+ Skills as compact label: value pairs.
1307
+ categories = [('Programming', 'Python, Java, C++'), ('Tools', 'Git, Docker')]
1308
+ """
1309
+ elements = []
1310
+ for cat, vals in categories:
1311
+ elements.append(Paragraph(f'<b>{cat}:</b> {vals}', body_style))
1312
+ return elements
1313
+
1314
+ # ── Build Document ──
1315
+ doc = SimpleDocTemplate(
1316
+ 'resume.pdf', pagesize=A4,
1317
+ leftMargin=1.5*cm, rightMargin=1.5*cm,
1318
+ topMargin=1.5*cm, bottomMargin=1.5*cm,
1319
+ title='Resume - Your Name',
1320
+ author='Z.ai', creator='Z.ai'
1321
+ )
1322
+
1323
+ story = []
1324
+
1325
+ # Header
1326
+ story.append(Paragraph('<b>YOUR NAME</b>', name_style))
1327
+ story.append(Paragraph(
1328
+ 'email@example.com | +86 138-0000-0000 | Shanghai, China | github.com/yourname',
1329
+ contact_style
1330
+ ))
1331
+
1332
+ # Summary
1333
+ story.extend(section_header('PROFESSIONAL SUMMARY'))
1334
+ story.append(Paragraph(
1335
+ 'Results-driven software engineer with 5+ years of experience in backend systems, '
1336
+ 'distributed computing, and cloud-native architectures. Led a team of 8 engineers '
1337
+ 'delivering a real-time data pipeline processing 2M+ events/sec.',
1338
+ body_style
1339
+ ))
1340
+
1341
+ # Experience
1342
+ story.extend(section_header('WORK EXPERIENCE'))
1343
+ story.extend(experience_entry(
1344
+ 'Senior Software Engineer', 'Tech Company Inc.', 'Jan 2022 - Present', 'Shanghai',
1345
+ [
1346
+ 'Designed and deployed a microservices architecture serving 10M daily active users',
1347
+ 'Reduced API latency by 40% through query optimisation and caching strategies',
1348
+ 'Mentored 3 junior engineers; established code review standards adopted team-wide',
1349
+ ]
1350
+ ))
1351
+ story.extend(experience_entry(
1352
+ 'Software Engineer', 'Startup Co.', 'Jul 2019 - Dec 2021', 'Beijing',
1353
+ [
1354
+ 'Built real-time recommendation engine using collaborative filtering (CTR +25%)',
1355
+ 'Implemented CI/CD pipeline reducing deployment time from 2 hours to 15 minutes',
1356
+ ]
1357
+ ))
1358
+
1359
+ # Education
1360
+ story.extend(section_header('EDUCATION'))
1361
+ story.extend(education_entry(
1362
+ 'M.Sc. Computer Science', 'Tsinghua University', '2017 - 2019',
1363
+ 'GPA: 3.8/4.0 | Thesis: Distributed Graph Processing on Heterogeneous Clusters'
1364
+ ))
1365
+ story.extend(education_entry(
1366
+ 'B.Eng. Software Engineering', 'Zhejiang University', '2013 - 2017'
1367
+ ))
1368
+
1369
+ # Skills
1370
+ story.extend(section_header('SKILLS'))
1371
+ story.extend(skills_row([
1372
+ ('Languages', 'Python, Java, Go, SQL, TypeScript'),
1373
+ ('Frameworks', 'Spring Boot, FastAPI, React, Kubernetes, Kafka'),
1374
+ ('Tools', 'Git, Docker, Terraform, AWS (EC2/S3/Lambda), PostgreSQL, Redis'),
1375
+ ]))
1376
+
1377
+ doc.build(story)
1378
+ ```
1379
+
1380
+ ### Resume Checklist
1381
+ - [ ] **1 page** (unless user says otherwise)
1382
+ - [ ] **No cover page, no TOC**
1383
+ - [ ] Tight margins (1.5cm all sides)
1384
+ - [ ] Name prominent at top (22-26pt)
1385
+ - [ ] Contact info single line, centered
1386
+ - [ ] Section headers with consistent separator style
1387
+ - [ ] Bullets concise - start with action verbs
1388
+ - [ ] Quantified achievements (%, $, count)
1389
+ - [ ] No photos, no icons, no colour blocks (ATS-safe)
1390
+ - [ ] Font: only registered fonts (Times New Roman / SimHei)
1391
+ - [ ] **⚠️ Minimum font size 12px (9pt)** - no text smaller than this anywhere
1392
+ - [ ] **Line breaks are language-aware** - no mid-word English breaks, no CJK punctuation orphans, no date range splits
1393
+ - [ ] **Page fill ≥85%** - no large blank area at bottom. If sparse, increase spacing/leading/font size adaptively
1394
+
1395
+ ---
1396
+
1397
+ ## Component Reference
1398
+
1399
+ ### Block types:
1400
+ | Type | Description | Notes |
1401
+ |------|-------------|-------|
1402
+ | h1 | 22pt + accent underline rule | KeepTogether with rule |
1403
+ | h2 | 15pt, dark | No rule, no accent |
1404
+ | h3 | 11.5pt bold | No accent |
1405
+ | body | 10.5pt justified, 17pt leading | Supports `<b>` `<i>` `<font>` |
1406
+ | bullet | Body size with `•` prefix | Unordered list |
1407
+ | numbered | Body size with N. prefix | Counter auto-resets |
1408
+ | callout | Accent left border 4px + light tint bg | Max one per section |
1409
+ | table | Accent header + alternating rows + outer box only | Supports fractional col_widths |
1410
+ | code | Courier 8.5pt + accent left border | Optional language label |
1411
+ | divider | Accent 1.2pt rule | Use sparingly |
1412
+ | caption | 8.5pt muted, centered | Below images/tables |
1413
+ | chart | matplotlib figure saved as PNG → `Image()` flowable | Generate chart in-script, `fig.savefig()` → embed. Set `plt.rcParams['font.sans-serif']=['SimHei']` for CJK. Always `tight_layout()`. **Must follow `typesetting/charts.md` rules**: delete top/right spines, dashed grid 20% opacity, donut default for pie, anti-stacking labels. |
1414
+ | quote | Body italic + left indent 24pt + muted accent left border 2px | For blockquotes / testimonials |
1415
+ | bibliography | Hanging indent (firstLineIndent=-24pt, leftIndent=24pt) | GB/T 7714 or APA format per language |
1416
+ | math | Rendered via `<super>` `<sub>` tags in Paragraph | For inline math; complex equations → use academic brief instead |
1417
+
1418
+ ### Header / footer:
1419
+ - Header: document title (left, 7.5pt, muted) + accent rule (1.5pt, full width)
1420
+ - Footer: author (left, 7.5pt, muted) + page number (right, 7.5pt, muted) + light rule above
1421
+
1422
+ ### Custom flowables (preferred over Table hacks):
1423
+ - **CalloutBox**: accent 4px left border + light tint background - cleaner than Table simulation
1424
+ - **BibliographyItem**: hanging indent reference entry
1425
+
1426
+ ---
1427
+
1428
+ ## Quick Reference
1429
+
1430
+ | Task | Best Tool | Command/Code |
1431
+ |------|-----------|--------------|
1432
+ | Create PDF (ReportLab) | reportlab | Canvas or Platypus |
1433
+ | Fill PDF forms | Process brief | `python3 "$PDF_SKILL_DIR/scripts/pdf.py" form.fill` or annotation workflow |
1434
+ | Merge PDFs | Process brief | `python3 "$PDF_SKILL_DIR/scripts/pdf.py" pages.merge` |
1435
+ | Extract text | Process brief | `python3 "$PDF_SKILL_DIR/scripts/pdf.py" extract.text` |
1436
+ | Extract tables | Process brief | `python3 "$PDF_SKILL_DIR/scripts/pdf.py" extract.table` |
1437
+
1438
+ ---
1439
+
1440
+ ## Document-Type Quick Reference
1441
+
1442
+ ### 📋 Invoice / Receipt
1443
+
1444
+ Key elements:
1445
+ - Company logo/name at top
1446
+ - Invoice number + date (right-aligned)
1447
+ - Seller/buyer info block (2-column layout)
1448
+ - Line items table: Item, Quantity, Unit Price, Amount
1449
+ - Total row with bold font
1450
+ - Tax info + payment terms at bottom
1451
+ - Stamp/seal placeholder (empty circle or rect with "Seal Here" text)
1452
+
1453
+ ```python
1454
+ # Invoice table pattern
1455
+ data = [['Item', 'Qty', 'Unit Price', 'Amount']]
1456
+ data += [[item['name'], item['qty'], item['price'], item['total']] for item in items]
1457
+ data.append(['', '', 'Total:', f'¥{total}'])
1458
+ ```
1459
+
1460
+ ### 📝 Contract / Legal Document
1461
+
1462
+ Key elements:
1463
+ - Title centered, bold, 18pt
1464
+ - Numbered clauses with auto-increment
1465
+ - Signature block at bottom: Party A / Party B with date line
1466
+ - Page numbers mandatory
1467
+
1468
+ ```python
1469
+ # Signature block pattern
1470
+ sig_data = [
1471
+ ['Party A (Seal): ________________', 'Party B (Seal): ________________'],
1472
+ ['Date: ____/____/________', 'Date: ____/____/________'],
1473
+ ]
1474
+ sig_table = Table(sig_data, colWidths=[250, 250])
1475
+ ```
1476
+
1477
+ ### 📊 Book / Long Document
1478
+
1479
+ For documents with 10+ pages:
1480
+ 1. Generate TOC with `TableOfContents()` from reportlab.platypus
1481
+ 2. Use `CondPageBreak(H1_ORPHAN_THRESHOLD)` before H1 headings (NOT `PageBreak()` — never force page breaks between chapters)
1482
+ 3. Add running headers/footers with chapter title + page number
1483
+ 4. Run `python3 "$PDF_SKILL_DIR/scripts/toc_validate.py" output.pdf` to verify TOC links
1484
+ 5. Consider using `bookmarks=True` for PDF outline navigation
1485
+
1486
+ ---
1487
+
1488
+ ### 📝 Exam / Quiz / Test Paper / Worksheet
1489
+
1490
+ **Exam papers have unique layout requirements. These rules are MANDATORY when generating any test/quiz/exam document.**
1491
+
1492
+ #### Numbering & Structure
1493
+ ```
1494
+ 一、选择题(每小题 3 分,共 30 分) ← Section header (宋体/黑体 14pt Bold)
1495
+
1496
+ 1. 以下哪个不是 Python 内置数据类型? ← Question stem (12pt)
1497
+ A. int ← Options: indented 24pt (2em)
1498
+ B. float ← Each option on new line or 2×2 grid
1499
+ C. array
1500
+ D. str
1501
+
1502
+ 2. 以下表达式的值为? ← Next question
1503
+ A. True B. False ← Short options: inline 2×2 grid OK
1504
+ C. None D. Error
1505
+ ```
1506
+
1507
+ #### Option Indentation (MANDATORY)
1508
+ ```python
1509
+ # ReportLab styles for exam papers
1510
+ question_style = ParagraphStyle(
1511
+ 'Question', fontSize=12, leading=16,
1512
+ leftIndent=0, firstLineIndent=0,
1513
+ spaceBefore=12, spaceAfter=4,
1514
+ )
1515
+ option_style = ParagraphStyle(
1516
+ 'Option', fontSize=12, leading=16,
1517
+ leftIndent=24, # ← MANDATORY: 24pt indent from question stem
1518
+ firstLineIndent=0,
1519
+ spaceBefore=2, spaceAfter=2,
1520
+ )
1521
+ ```
1522
+
1523
+ #### Option Layout Decision
1524
+ ```python
1525
+ def format_options(options):
1526
+ """
1527
+ Decide option layout based on content length.
1528
+ Short options (≤4 chars each, ≤4 options) → 2×2 grid table
1529
+ Long options or >4 options → vertical list, one per line
1530
+ """
1531
+ max_len = max(len(opt) for opt in options)
1532
+ if len(options) <= 4 and max_len <= 6: # CJK: 4 chars; Latin: 6 chars
1533
+ # 2×2 grid using Table
1534
+ grid = Table(
1535
+ [[options[0], options[1]], [options[2], options[3]]],
1536
+ colWidths=[200, 200], hAlign='LEFT'
1537
+ )
1538
+ grid.setStyle(TableStyle([
1539
+ ('LEFTPADDING', (0,0), (-1,-1), 24), # Match option indent
1540
+ ('VALIGN', (0,0), (-1,-1), 'TOP'),
1541
+ ]))
1542
+ return grid
1543
+ else:
1544
+ # Vertical list
1545
+ return [Paragraph(f'{opt}', option_style) for opt in options]
1546
+ ```
1547
+
1548
+ #### Answer Space Reservation (MANDATORY)
1549
+
1550
+ **Every question MUST have adequate answer space. No exceptions.**
1551
+
1552
+ | Question Type | Minimum Space | Implementation |
1553
+ |--------------|---------------|----------------|
1554
+ | Multiple choice | 0 extra (options are the answer) | Just question + options |
1555
+ | Fill-in-the-blank | Inline underline, min 80pt width | `<u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u>` or ReportLab `HRFlowable` |
1556
+ | Short answer | 40-60pt (2-3 lines) | `Spacer(1, 50)` |
1557
+ | Calculation / math work | 120-200pt (6-10 lines) | `Spacer(1, 160)` with light guide lines |
1558
+ | Essay / long answer | 200-400pt (10-20 lines) | `Spacer(1, 300)` with light guide lines |
1559
+ | Proof / derivation | 160-250pt (8-12 lines) | `Spacer(1, 200)` |
1560
+
1561
+ ```python
1562
+ # Answer line helper — light dashed lines for handwriting
1563
+ def add_answer_lines(story, num_lines=8, line_spacing=20):
1564
+ """Add light guide lines for handwritten answers."""
1565
+ for i in range(num_lines):
1566
+ story.append(Spacer(1, line_spacing))
1567
+ story.append(HRFlowable(
1568
+ width='90%', thickness=0.3,
1569
+ color=colors.Color(0.8, 0.8, 0.8), # Light gray
1570
+ dash=[4, 4], # Dashed
1571
+ spaceAfter=0, spaceBefore=0
1572
+ ))
1573
+ ```
1574
+
1575
+ #### Page Density
1576
+ - `spaceBefore=12pt` between questions minimum
1577
+ - `spaceBefore=24pt` before section headers (一、二、三)
1578
+ - Score indicator after question number: `1. (分值: 5分)` or `1. [5 pts]`
1579
+ - Page header: exam title + time limit + total score
1580
+ - No cover page unless explicitly requested
1581
+
1582
+ ---
1583
+
1584
+ ## Data-to-Ink Ratio Rules (MANDATORY for Reports)
1585
+
1586
+ **CRITICAL: Do NOT write long paragraphs to describe data trends.** You MUST extract metrics and trends into structured visual elements.
1587
+
1588
+ ### Pattern Detection Table
1589
+
1590
+ Before writing ANY body paragraph, scan the text. If you find any of these patterns, extract them:
1591
+
1592
+ | Raw text pattern | ❌ FORBIDDEN | ✅ REQUIRED visual form |
1593
+ |-----------------|-------------|----------------------|
1594
+ | "revenue grew 12% to $4.2M" | Bury in paragraph prose | CalloutBox with bold `+12%` + `$4.2M` |
1595
+ | "latency dropped from 120ms to 75ms" | Long explanatory sentence | CalloutBox or metrics table row |
1596
+ | "Q1→Q2→Q3: 10%→25%→40%" | Inline numbers in text | Chart (matplotlib PNG → `Image()`) |
1597
+ | "first...second...third..." steps | Paragraph with ordinal words | Numbered Table or process list |
1598
+ | "compared to last year / vs Q2" | Nested comparisons in prose | Side-by-side comparison table |
1599
+ | "accounted for 60% of total" | Percentage in paragraph | Pie chart or stacked bar chart |
1600
+
1601
+ ### ReportLab CalloutBox Template
1602
+
1603
+ Use this pattern for extracted metrics - it's visually clean and takes only 5 lines:
1604
+
1605
+ ```python
1606
+ stat_style = ParagraphStyle(
1607
+ name='StatBig', fontName='Times New Roman', fontSize=22,
1608
+ leading=26, textColor=ACCENT, alignment=TA_CENTER # From palette
1609
+ )
1610
+ label_style = ParagraphStyle(
1611
+ name='StatLabel', fontName='Times New Roman', fontSize=9,
1612
+ leading=12, textColor=TEXT_MUTED, alignment=TA_CENTER # From palette
1613
+ )
1614
+
1615
+ callout = Table(
1616
+ [[Paragraph('<b>+12%</b>', stat_style)],
1617
+ [Paragraph('Revenue Growth vs Q2', label_style)]],
1618
+ colWidths=[160]
1619
+ )
1620
+ callout.setStyle(TableStyle([
1621
+ ('BACKGROUND', (0,0), (-1,-1), BG_SURFACE), # From palette --c-mid
1622
+ ('BOX', (0,0), (-1,-1), 1, ACCENT), # From palette --c-accent
1623
+ ('TOPPADDING', (0,0), (-1,-1), 10),
1624
+ ('BOTTOMPADDING', (0,0), (-1,-1), 10),
1625
+ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
1626
+ ]))
1627
+ story.append(KeepTogether(callout))
1628
+ ```
1629
+
1630
+ ### Cover Pages (HTML/Playwright)
1631
+ When the cover routes through Playwright:
1632
+ - Use `Delta_Widget` components for KPIs and metrics.
1633
+ - Use `Process_List` components for workflows and timelines.
1634
+ - Use `Sidenote_Block` components (in `tufte_report` archetype) for citations and supplementary data.
1635
+ - For data-heavy pages, add `data_points` arrays to any component - the engine renders them as content-aware background curves.
1636
+
1637
+ ---
1638
+
1639
+ ## Critical Reminders Checklist
1640
+
1641
+ Before submitting code, verify:
1642
+
1643
+ - [ ] **Font restriction**: Only 6 registered fonts used
1644
+ - [ ] **Font family registered**: `registerFontFamily()` called for all used fonts
1645
+ - [ ] **Mixed language**: `install_font_fallback()` called after font registration (auto handles `<font>` wrapping)
1646
+ - [ ] **Rich text tags**: Only inside `Paragraph()` objects
1647
+ - [ ] **Table cells**: ALL text wrapped in `Paragraph()`
1648
+ - [ ] **Scientific notation**: Large/small numbers use `<super>` tags
1649
+ - [ ] **Chinese text**: `wordWrap='CJK'` in ParagraphStyle
1650
+ - [ ] **Line breaks**: Using `<br/>` not `\n`
1651
+ - [ ] **Headings**: Bold with `<b>` tags
1652
+ - [ ] **Table headers**: White bold text on dark blue (#1F4E79)
1653
+ - [ ] **Metadata**: Title matches filename, Author/Creator = "Z.ai"
1654
+ - [ ] **Sanitization**: Code sanitized before execution
1655
+ - [ ] **Post-build metadata**: `pdf.py meta.brand` called after build
1656
+ - [ ] **Post-build blank page cleanup**: `pdf.py pages.clean` called after build
1657
+ - [ ] **Glyph check**: `pdf.py font.check` run to verify no missing glyphs
1658
+ - [ ] **TOC check**: `pdf.py toc.check` run if document has TOC (entries, pages, links)
1659
+ - [ ] **PDF QA scan**: `pdf_qa.py` run to verify page consistency, CJK punctuation, overflow, margins, table centering, font embedding, metadata