@nguyenphp/antigravity-marketing 1.0.16 → 1.0.19

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 (376) hide show
  1. package/README.md +187 -74
  2. package/bin/index.js +4 -4
  3. package/package.json +4 -3
  4. package/templates/.agent/agents/backend-specialist.md +263 -0
  5. package/templates/.agent/agents/database-architect.md +226 -0
  6. package/templates/.agent/agents/debugger.md +225 -0
  7. package/templates/.agent/agents/devops-engineer.md +242 -0
  8. package/templates/.agent/agents/documentation-writer.md +104 -0
  9. package/templates/.agent/agents/explorer-agent.md +73 -0
  10. package/templates/.agent/agents/frontend-specialist.md +527 -0
  11. package/templates/.agent/agents/game-developer.md +162 -0
  12. package/templates/.agent/agents/mobile-developer.md +377 -0
  13. package/templates/.agent/agents/orchestrator.md +400 -0
  14. package/templates/.agent/agents/penetration-tester.md +188 -0
  15. package/templates/.agent/agents/performance-optimizer.md +187 -0
  16. package/templates/.agent/agents/project-planner.md +403 -0
  17. package/templates/.agent/agents/security-auditor.md +170 -0
  18. package/templates/.agent/agents/seo-specialist.md +111 -0
  19. package/templates/.agent/agents/test-engineer.md +158 -0
  20. package/templates/.agent/rules/GEMINI.md +248 -0
  21. package/templates/.agent/skills/analytics-marketing/SKILL.md +172 -324
  22. package/templates/.agent/skills/api-patterns/SKILL.md +81 -0
  23. package/templates/.agent/skills/api-patterns/api-style.md +42 -0
  24. package/templates/.agent/skills/api-patterns/auth.md +24 -0
  25. package/templates/.agent/skills/api-patterns/documentation.md +26 -0
  26. package/templates/.agent/skills/api-patterns/graphql.md +41 -0
  27. package/templates/.agent/skills/api-patterns/rate-limiting.md +31 -0
  28. package/templates/.agent/skills/api-patterns/response.md +37 -0
  29. package/templates/.agent/skills/api-patterns/rest.md +40 -0
  30. package/templates/.agent/skills/api-patterns/scripts/api_validator.py +211 -0
  31. package/templates/.agent/skills/api-patterns/security-testing.md +122 -0
  32. package/templates/.agent/skills/api-patterns/trpc.md +41 -0
  33. package/templates/.agent/skills/api-patterns/versioning.md +22 -0
  34. package/templates/.agent/skills/app-builder/SKILL.md +75 -0
  35. package/templates/.agent/skills/app-builder/agent-coordination.md +71 -0
  36. package/templates/.agent/skills/app-builder/feature-building.md +53 -0
  37. package/templates/.agent/skills/app-builder/project-detection.md +34 -0
  38. package/templates/.agent/skills/app-builder/scaffolding.md +118 -0
  39. package/templates/.agent/skills/app-builder/tech-stack.md +40 -0
  40. package/templates/.agent/skills/app-builder/templates/SKILL.md +39 -0
  41. package/templates/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -0
  42. package/templates/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -0
  43. package/templates/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -0
  44. package/templates/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -0
  45. package/templates/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +83 -0
  46. package/templates/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -0
  47. package/templates/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -0
  48. package/templates/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +82 -0
  49. package/templates/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +100 -0
  50. package/templates/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +106 -0
  51. package/templates/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +101 -0
  52. package/templates/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -0
  53. package/templates/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +93 -0
  54. package/templates/.agent/skills/architecture/SKILL.md +55 -0
  55. package/templates/.agent/skills/architecture/context-discovery.md +43 -0
  56. package/templates/.agent/skills/architecture/examples.md +94 -0
  57. package/templates/.agent/skills/architecture/pattern-selection.md +68 -0
  58. package/templates/.agent/skills/architecture/patterns-reference.md +50 -0
  59. package/templates/.agent/skills/architecture/trade-off-analysis.md +77 -0
  60. package/templates/.agent/skills/banner-design/SKILL.md +192 -0
  61. package/templates/.agent/skills/banner-design/references/banner-sizes-and-styles.md +118 -0
  62. package/templates/.agent/skills/bash-linux/SKILL.md +199 -0
  63. package/templates/.agent/skills/behavioral-modes/SKILL.md +242 -0
  64. package/templates/.agent/skills/brainstorming/SKILL.md +163 -0
  65. package/templates/.agent/skills/brainstorming/dynamic-questioning.md +350 -0
  66. package/templates/.agent/skills/brand/SKILL.md +97 -0
  67. package/templates/.agent/skills/brand/references/approval-checklist.md +169 -0
  68. package/templates/.agent/skills/brand/references/asset-organization.md +157 -0
  69. package/templates/.agent/skills/brand/references/brand-guideline-template.md +140 -0
  70. package/templates/.agent/skills/brand/references/color-palette-management.md +186 -0
  71. package/templates/.agent/skills/brand/references/consistency-checklist.md +94 -0
  72. package/templates/.agent/skills/brand/references/logo-usage-rules.md +185 -0
  73. package/templates/.agent/skills/brand/references/messaging-framework.md +85 -0
  74. package/templates/.agent/skills/brand/references/typography-specifications.md +214 -0
  75. package/templates/.agent/skills/brand/references/update.md +118 -0
  76. package/templates/.agent/skills/brand/references/visual-identity.md +96 -0
  77. package/templates/.agent/skills/brand/references/voice-framework.md +88 -0
  78. package/templates/.agent/skills/brand/scripts/extract-colors.cjs +341 -0
  79. package/templates/.agent/skills/brand/scripts/inject-brand-context.cjs +349 -0
  80. package/templates/.agent/skills/brand/scripts/sync-brand-to-tokens.cjs +266 -0
  81. package/templates/.agent/skills/brand/scripts/validate-asset.cjs +387 -0
  82. package/templates/.agent/skills/brand/templates/brand-guidelines-starter.md +275 -0
  83. package/templates/.agent/skills/clean-code/SKILL.md +201 -0
  84. package/templates/.agent/skills/code-review-checklist/SKILL.md +109 -0
  85. package/templates/.agent/skills/copywriting/SKILL.md +250 -0
  86. package/templates/.agent/skills/database-design/SKILL.md +52 -0
  87. package/templates/.agent/skills/database-design/database-selection.md +43 -0
  88. package/templates/.agent/skills/database-design/indexing.md +39 -0
  89. package/templates/.agent/skills/database-design/migrations.md +48 -0
  90. package/templates/.agent/skills/database-design/optimization.md +36 -0
  91. package/templates/.agent/skills/database-design/orm-selection.md +30 -0
  92. package/templates/.agent/skills/database-design/schema-design.md +56 -0
  93. package/templates/.agent/skills/database-design/scripts/schema_validator.py +172 -0
  94. package/templates/.agent/skills/deployment-procedures/SKILL.md +241 -0
  95. package/templates/.agent/skills/docker-expert/SKILL.md +409 -0
  96. package/templates/.agent/skills/frontend-design/animation-guide.md +331 -0
  97. package/templates/.agent/skills/frontend-design/color-system.md +311 -0
  98. package/templates/.agent/skills/frontend-design/decision-trees.md +418 -0
  99. package/templates/.agent/skills/frontend-design/motion-graphics.md +306 -0
  100. package/templates/.agent/skills/frontend-design/scripts/accessibility_checker.py +183 -0
  101. package/templates/.agent/skills/frontend-design/scripts/ux_audit.py +722 -0
  102. package/templates/.agent/skills/frontend-design/typography-system.md +345 -0
  103. package/templates/.agent/skills/frontend-design/ux-psychology.md +541 -0
  104. package/templates/.agent/skills/frontend-design/visual-effects.md +383 -0
  105. package/templates/.agent/skills/frontend-slides/SKILL.md +92 -0
  106. package/templates/.agent/skills/frontend-slides/STYLE_PRESETS.md +347 -0
  107. package/templates/.agent/skills/frontend-slides/animation-patterns.md +110 -0
  108. package/templates/.agent/skills/frontend-slides/examples/n8n-jupviec-automation.html +789 -0
  109. package/templates/.agent/skills/frontend-slides/examples/n8n-jupviec-automation.pptx +0 -0
  110. package/templates/.agent/skills/frontend-slides/html-template.md +347 -0
  111. package/templates/.agent/skills/frontend-slides/scripts/export-pptx.py +58 -0
  112. package/templates/.agent/skills/frontend-slides/scripts/extract-pptx.py +96 -0
  113. package/templates/.agent/skills/frontend-slides/viewport-base.css +153 -0
  114. package/templates/.agent/skills/game-development/2d-games/SKILL.md +119 -0
  115. package/templates/.agent/skills/game-development/3d-games/SKILL.md +135 -0
  116. package/templates/.agent/skills/game-development/SKILL.md +167 -0
  117. package/templates/.agent/skills/game-development/game-art/SKILL.md +185 -0
  118. package/templates/.agent/skills/game-development/game-audio/SKILL.md +190 -0
  119. package/templates/.agent/skills/game-development/game-design/SKILL.md +129 -0
  120. package/templates/.agent/skills/game-development/mobile-games/SKILL.md +108 -0
  121. package/templates/.agent/skills/game-development/multiplayer/SKILL.md +132 -0
  122. package/templates/.agent/skills/game-development/pc-games/SKILL.md +144 -0
  123. package/templates/.agent/skills/game-development/vr-ar/SKILL.md +123 -0
  124. package/templates/.agent/skills/game-development/web-games/SKILL.md +150 -0
  125. package/templates/.agent/skills/geo-fundamentals/SKILL.md +156 -0
  126. package/templates/.agent/skills/geo-fundamentals/scripts/geo_checker.py +289 -0
  127. package/templates/.agent/skills/growth-engine/SKILL.md +244 -0
  128. package/templates/.agent/skills/i18n-localization/SKILL.md +154 -0
  129. package/templates/.agent/skills/i18n-localization/scripts/i18n_checker.py +241 -0
  130. package/templates/.agent/skills/lint-and-validate/SKILL.md +45 -0
  131. package/templates/.agent/skills/lint-and-validate/scripts/lint_runner.py +172 -0
  132. package/templates/.agent/skills/lint-and-validate/scripts/type_coverage.py +173 -0
  133. package/templates/.agent/skills/marketing-report-expert/SKILL.md +70 -0
  134. package/templates/.agent/skills/mcp-builder/SKILL.md +176 -0
  135. package/templates/.agent/skills/minimax-docx/LICENSE +21 -0
  136. package/templates/.agent/skills/minimax-docx/SKILL.md +274 -0
  137. package/templates/.agent/skills/minimax-docx/assets/styles/academic_styles.xml +250 -0
  138. package/templates/.agent/skills/minimax-docx/assets/styles/corporate_styles.xml +284 -0
  139. package/templates/.agent/skills/minimax-docx/assets/styles/default_styles.xml +449 -0
  140. package/templates/.agent/skills/minimax-docx/assets/xsd/aesthetic-rules.xsd +470 -0
  141. package/templates/.agent/skills/minimax-docx/assets/xsd/business-rules.xsd +130 -0
  142. package/templates/.agent/skills/minimax-docx/assets/xsd/common-types.xsd +159 -0
  143. package/templates/.agent/skills/minimax-docx/assets/xsd/wml-subset.xsd +589 -0
  144. package/templates/.agent/skills/minimax-docx/references/cjk_typography.md +357 -0
  145. package/templates/.agent/skills/minimax-docx/references/cjk_university_template_guide.md +184 -0
  146. package/templates/.agent/skills/minimax-docx/references/comments_guide.md +191 -0
  147. package/templates/.agent/skills/minimax-docx/references/design_good_bad_examples.md +829 -0
  148. package/templates/.agent/skills/minimax-docx/references/design_principles.md +819 -0
  149. package/templates/.agent/skills/minimax-docx/references/openxml_element_order.md +308 -0
  150. package/templates/.agent/skills/minimax-docx/references/openxml_encyclopedia_part1.md +4061 -0
  151. package/templates/.agent/skills/minimax-docx/references/openxml_encyclopedia_part2.md +2820 -0
  152. package/templates/.agent/skills/minimax-docx/references/openxml_encyclopedia_part3.md +3381 -0
  153. package/templates/.agent/skills/minimax-docx/references/openxml_namespaces.md +82 -0
  154. package/templates/.agent/skills/minimax-docx/references/openxml_units.md +72 -0
  155. package/templates/.agent/skills/minimax-docx/references/scenario_a_create.md +284 -0
  156. package/templates/.agent/skills/minimax-docx/references/scenario_b_edit_content.md +295 -0
  157. package/templates/.agent/skills/minimax-docx/references/scenario_c_apply_template.md +456 -0
  158. package/templates/.agent/skills/minimax-docx/references/track_changes_guide.md +200 -0
  159. package/templates/.agent/skills/minimax-docx/references/troubleshooting.md +506 -0
  160. package/templates/.agent/skills/minimax-docx/references/typography_guide.md +294 -0
  161. package/templates/.agent/skills/minimax-docx/references/xsd_validation_guide.md +158 -0
  162. package/templates/.agent/skills/minimax-docx/scripts/doc_to_docx.sh +40 -0
  163. package/templates/.agent/skills/minimax-docx/scripts/docx_preview.sh +37 -0
  164. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Cli/MiniMaxAIDocx.Cli.csproj +19 -0
  165. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Cli/Program.cs +18 -0
  166. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/AnalyzeCommand.cs +147 -0
  167. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/ApplyTemplateCommand.cs +322 -0
  168. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/CreateCommand.cs +324 -0
  169. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/DiffCommand.cs +155 -0
  170. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/EditContentCommand.cs +487 -0
  171. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/FixOrderCommand.cs +108 -0
  172. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/MergeRunsCommand.cs +122 -0
  173. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Commands/ValidateCommand.cs +107 -0
  174. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/MiniMaxAIDocx.Core.csproj +15 -0
  175. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/CommentSynchronizer.cs +169 -0
  176. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/ElementOrder.cs +80 -0
  177. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/NamespaceConstants.cs +42 -0
  178. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/RunMerger.cs +81 -0
  179. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/StyleAnalyzer.cs +81 -0
  180. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/TrackChangesHelper.cs +99 -0
  181. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/OpenXml/UnitConverter.cs +23 -0
  182. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/AestheticRecipeSamples.cs +1832 -0
  183. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/AestheticRecipeSamples_Batch1.cs +910 -0
  184. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/AestheticRecipeSamples_Batch2.cs +999 -0
  185. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/AestheticRecipeSamples_Batch3.cs +1048 -0
  186. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/AestheticRecipeSamples_Batch4.cs +1038 -0
  187. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/CharacterFormattingSamples.cs +1020 -0
  188. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/DocumentCreationSamples.cs +1121 -0
  189. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/FieldAndTocSamples.cs +624 -0
  190. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/FootnoteAndCommentSamples.cs +675 -0
  191. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/HeaderFooterSamples.cs +838 -0
  192. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/ImageSamples.cs +917 -0
  193. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/ListAndNumberingSamples.cs +826 -0
  194. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/ParagraphFormattingSamples.cs +1199 -0
  195. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/StyleSystemSamples.cs +1487 -0
  196. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/TableSamples.cs +1163 -0
  197. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Samples/TrackChangesSamples.cs +595 -0
  198. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Typography/CjkHelper.cs +39 -0
  199. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Typography/FontDefaults.cs +24 -0
  200. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Typography/PageSizes.cs +20 -0
  201. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Validation/BusinessRuleValidator.cs +224 -0
  202. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Validation/GateCheckValidator.cs +148 -0
  203. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Validation/ValidationResult.cs +23 -0
  204. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.Core/Validation/XsdValidator.cs +69 -0
  205. package/templates/.agent/skills/minimax-docx/scripts/dotnet/MiniMaxAIDocx.slnx +4 -0
  206. package/templates/.agent/skills/minimax-docx/scripts/env_check.sh +196 -0
  207. package/templates/.agent/skills/minimax-docx/scripts/setup.ps1 +274 -0
  208. package/templates/.agent/skills/minimax-docx/scripts/setup.sh +504 -0
  209. package/templates/.agent/skills/minimax-multimodal-toolkit/SKILL.md +359 -0
  210. package/templates/.agent/skills/minimax-pdf/README.md +222 -0
  211. package/templates/.agent/skills/minimax-pdf/SKILL.md +201 -0
  212. package/templates/.agent/skills/minimax-pdf/design/design.md +381 -0
  213. package/templates/.agent/skills/minimax-pdf/scripts/cover.py +1579 -0
  214. package/templates/.agent/skills/minimax-pdf/scripts/fill_inspect.py +200 -0
  215. package/templates/.agent/skills/minimax-pdf/scripts/fill_write.py +242 -0
  216. package/templates/.agent/skills/minimax-pdf/scripts/make.sh +491 -0
  217. package/templates/.agent/skills/minimax-pdf/scripts/merge.py +112 -0
  218. package/templates/.agent/skills/minimax-pdf/scripts/palette.py +559 -0
  219. package/templates/.agent/skills/minimax-pdf/scripts/reformat_parse.py +374 -0
  220. package/templates/.agent/skills/minimax-pdf/scripts/render_body.py +1055 -0
  221. package/templates/.agent/skills/minimax-pdf/scripts/render_cover.cjs +111 -0
  222. package/templates/.agent/skills/minimax-xlsx/SKILL.md +138 -0
  223. package/templates/.agent/skills/minimax-xlsx/references/create.md +691 -0
  224. package/templates/.agent/skills/minimax-xlsx/references/edit.md +684 -0
  225. package/templates/.agent/skills/minimax-xlsx/references/fix.md +37 -0
  226. package/templates/.agent/skills/minimax-xlsx/references/format.md +768 -0
  227. package/templates/.agent/skills/minimax-xlsx/references/ooxml-cheatsheet.md +231 -0
  228. package/templates/.agent/skills/minimax-xlsx/references/read-analyze.md +97 -0
  229. package/templates/.agent/skills/minimax-xlsx/references/validate.md +772 -0
  230. package/templates/.agent/skills/minimax-xlsx/scripts/formula_check.py +422 -0
  231. package/templates/.agent/skills/minimax-xlsx/scripts/libreoffice_recalc.py +248 -0
  232. package/templates/.agent/skills/minimax-xlsx/scripts/shared_strings_builder.py +163 -0
  233. package/templates/.agent/skills/minimax-xlsx/scripts/style_audit.py +575 -0
  234. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_add_column.py +395 -0
  235. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_insert_row.py +274 -0
  236. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_pack.py +87 -0
  237. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_reader.py +362 -0
  238. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_shift_rows.py +396 -0
  239. package/templates/.agent/skills/minimax-xlsx/scripts/xlsx_unpack.py +130 -0
  240. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/[Content_Types].xml +9 -0
  241. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/_rels/.rels +6 -0
  242. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/xl/_rels/workbook.xml.rels +19 -0
  243. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/xl/sharedStrings.xml +33 -0
  244. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/xl/styles.xml +160 -0
  245. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/xl/workbook.xml +30 -0
  246. package/templates/.agent/skills/minimax-xlsx/templates/minimal_xlsx/xl/worksheets/sheet1.xml +70 -0
  247. package/templates/.agent/skills/mobile-design/SKILL.md +394 -0
  248. package/templates/.agent/skills/mobile-design/decision-trees.md +516 -0
  249. package/templates/.agent/skills/mobile-design/mobile-backend.md +491 -0
  250. package/templates/.agent/skills/mobile-design/mobile-color-system.md +420 -0
  251. package/templates/.agent/skills/mobile-design/mobile-debugging.md +122 -0
  252. package/templates/.agent/skills/mobile-design/mobile-design-thinking.md +357 -0
  253. package/templates/.agent/skills/mobile-design/mobile-navigation.md +458 -0
  254. package/templates/.agent/skills/mobile-design/mobile-performance.md +767 -0
  255. package/templates/.agent/skills/mobile-design/mobile-testing.md +356 -0
  256. package/templates/.agent/skills/mobile-design/mobile-typography.md +433 -0
  257. package/templates/.agent/skills/mobile-design/platform-android.md +666 -0
  258. package/templates/.agent/skills/mobile-design/platform-ios.md +561 -0
  259. package/templates/.agent/skills/mobile-design/scripts/mobile_audit.py +670 -0
  260. package/templates/.agent/skills/mobile-design/touch-psychology.md +537 -0
  261. package/templates/.agent/skills/nestjs-expert/SKILL.md +552 -0
  262. package/templates/.agent/skills/nextjs-best-practices/SKILL.md +203 -0
  263. package/templates/.agent/skills/nodejs-best-practices/SKILL.md +333 -0
  264. package/templates/.agent/skills/parallel-agents/SKILL.md +175 -0
  265. package/templates/.agent/skills/performance-profiling/SKILL.md +143 -0
  266. package/templates/.agent/skills/performance-profiling/scripts/lighthouse_audit.py +76 -0
  267. package/templates/.agent/skills/plan-writing/SKILL.md +152 -0
  268. package/templates/.agent/skills/powershell-windows/SKILL.md +167 -0
  269. package/templates/.agent/skills/ppc-advertising/SKILL.md +183 -475
  270. package/templates/.agent/skills/pptx-generator/SKILL.md +249 -0
  271. package/templates/.agent/skills/pptx-generator/references/design-system.md +392 -0
  272. package/templates/.agent/skills/pptx-generator/references/editing.md +162 -0
  273. package/templates/.agent/skills/pptx-generator/references/pitfalls.md +112 -0
  274. package/templates/.agent/skills/pptx-generator/references/pptxgenjs.md +420 -0
  275. package/templates/.agent/skills/pptx-generator/references/slide-types.md +413 -0
  276. package/templates/.agent/skills/prisma-expert/SKILL.md +355 -0
  277. package/templates/.agent/skills/python-patterns/SKILL.md +441 -0
  278. package/templates/.agent/skills/react-patterns/SKILL.md +198 -0
  279. package/templates/.agent/skills/red-team-tactics/SKILL.md +199 -0
  280. package/templates/.agent/skills/remotion-best-practices/SKILL.md +45 -111
  281. package/templates/.agent/skills/remotion-best-practices/rules/3d.md +4 -4
  282. package/templates/.agent/skills/remotion-best-practices/rules/animations.md +5 -7
  283. package/templates/.agent/skills/remotion-best-practices/rules/assets/charts-bar-chart.tsx +173 -0
  284. package/templates/.agent/skills/remotion-best-practices/rules/assets/text-animations-typewriter.tsx +100 -0
  285. package/templates/.agent/skills/remotion-best-practices/rules/assets/text-animations-word-highlight.tsx +103 -0
  286. package/templates/.agent/skills/remotion-best-practices/rules/assets.md +78 -0
  287. package/templates/.agent/skills/remotion-best-practices/rules/audio-visualization.md +198 -0
  288. package/templates/.agent/skills/remotion-best-practices/rules/audio.md +1 -4
  289. package/templates/.agent/skills/remotion-best-practices/rules/calculate-metadata.md +47 -17
  290. package/templates/.agent/skills/remotion-best-practices/rules/can-decode.md +75 -0
  291. package/templates/.agent/skills/remotion-best-practices/rules/charts.md +80 -48
  292. package/templates/.agent/skills/remotion-best-practices/rules/compositions.md +22 -14
  293. package/templates/.agent/skills/remotion-best-practices/rules/display-captions.md +79 -21
  294. package/templates/.agent/skills/remotion-best-practices/rules/extract-frames.md +229 -0
  295. package/templates/.agent/skills/remotion-best-practices/rules/ffmpeg.md +38 -0
  296. package/templates/.agent/skills/remotion-best-practices/rules/fonts.md +96 -54
  297. package/templates/.agent/skills/remotion-best-practices/rules/get-audio-duration.md +58 -0
  298. package/templates/.agent/skills/remotion-best-practices/rules/get-video-dimensions.md +68 -0
  299. package/templates/.agent/skills/remotion-best-practices/rules/get-video-duration.md +60 -0
  300. package/templates/.agent/skills/remotion-best-practices/rules/gifs.md +21 -18
  301. package/templates/.agent/skills/remotion-best-practices/rules/images.md +6 -2
  302. package/templates/.agent/skills/remotion-best-practices/rules/import-srt-captions.md +69 -0
  303. package/templates/.agent/skills/remotion-best-practices/rules/light-leaks.md +73 -0
  304. package/templates/.agent/skills/remotion-best-practices/rules/lottie.md +10 -7
  305. package/templates/.agent/skills/remotion-best-practices/rules/maps.md +412 -0
  306. package/templates/.agent/skills/remotion-best-practices/rules/measuring-dom-nodes.md +34 -0
  307. package/templates/.agent/skills/remotion-best-practices/rules/measuring-text.md +140 -0
  308. package/templates/.agent/skills/remotion-best-practices/rules/parameters.md +109 -0
  309. package/templates/.agent/skills/remotion-best-practices/rules/sequencing.md +13 -1
  310. package/templates/.agent/skills/remotion-best-practices/rules/sfx.md +26 -0
  311. package/templates/.agent/skills/remotion-best-practices/rules/subtitles.md +36 -0
  312. package/templates/.agent/skills/remotion-best-practices/rules/tailwind.md +11 -0
  313. package/templates/.agent/skills/remotion-best-practices/rules/text-animations.md +4 -115
  314. package/templates/.agent/skills/remotion-best-practices/rules/timing.md +19 -19
  315. package/templates/.agent/skills/remotion-best-practices/rules/transcribe-captions.md +70 -0
  316. package/templates/.agent/skills/remotion-best-practices/rules/transitions.md +117 -42
  317. package/templates/.agent/skills/remotion-best-practices/rules/transparent-videos.md +106 -0
  318. package/templates/.agent/skills/remotion-best-practices/rules/trimming.md +51 -0
  319. package/templates/.agent/skills/remotion-best-practices/rules/voiceover.md +99 -0
  320. package/templates/.agent/skills/seo-fundamentals/SKILL.md +83 -441
  321. package/templates/.agent/skills/seo-fundamentals/scripts/seo_checker.py +219 -0
  322. package/templates/.agent/skills/server-management/SKILL.md +161 -0
  323. package/templates/.agent/skills/systematic-debugging/SKILL.md +109 -0
  324. package/templates/.agent/skills/tdd-workflow/SKILL.md +149 -0
  325. package/templates/.agent/skills/testing-patterns/SKILL.md +178 -0
  326. package/templates/.agent/skills/testing-patterns/scripts/test_runner.py +219 -0
  327. package/templates/.agent/skills/tutorial-video-expert/SKILL.md +88 -0
  328. package/templates/.agent/skills/typescript-expert/SKILL.md +429 -0
  329. package/templates/.agent/skills/ui-ux-pro-max/SKILL.md +1 -1
  330. package/templates/.agent/skills/ui-ux-pro-max/data/charts.csv +26 -0
  331. package/templates/.agent/skills/ui-ux-pro-max/data/colors.csv +97 -0
  332. package/templates/.agent/skills/ui-ux-pro-max/data/icons.csv +101 -0
  333. package/templates/.agent/skills/ui-ux-pro-max/data/landing.csv +31 -0
  334. package/templates/.agent/skills/ui-ux-pro-max/data/products.csv +97 -0
  335. package/templates/.agent/skills/ui-ux-pro-max/data/prompts.csv +24 -0
  336. package/templates/.agent/skills/ui-ux-pro-max/data/react-performance.csv +45 -0
  337. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  338. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  339. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  340. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  341. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  342. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  343. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/react.csv +54 -0
  344. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  345. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  346. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  347. package/templates/.agent/skills/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  348. package/templates/.agent/skills/ui-ux-pro-max/data/styles.csv +59 -0
  349. package/templates/.agent/skills/ui-ux-pro-max/data/typography.csv +58 -0
  350. package/templates/.agent/skills/ui-ux-pro-max/data/ui-reasoning.csv +101 -0
  351. package/templates/.agent/skills/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  352. package/templates/.agent/skills/ui-ux-pro-max/data/web-interface.csv +31 -0
  353. package/templates/.agent/skills/ui-ux-pro-max/scripts/core.py +257 -0
  354. package/templates/.agent/skills/ui-ux-pro-max/scripts/design_system.py +487 -0
  355. package/templates/.agent/skills/ui-ux-pro-max/scripts/search.py +76 -0
  356. package/templates/.agent/skills/vision-analysis/SKILL.md +174 -0
  357. package/templates/.agent/skills/vue-expert/SKILL.md +374 -0
  358. package/templates/.agent/skills/vulnerability-scanner/SKILL.md +276 -0
  359. package/templates/.agent/skills/vulnerability-scanner/checklists.md +121 -0
  360. package/templates/.agent/skills/vulnerability-scanner/scripts/security_scan.py +458 -0
  361. package/templates/.agent/skills/webapp-testing/SKILL.md +187 -0
  362. package/templates/.agent/skills/webapp-testing/scripts/playwright_runner.py +173 -0
  363. package/templates/.agent/workflows/analyze.md +3 -0
  364. package/templates/.agent/workflows/brainstorm.md +113 -0
  365. package/templates/.agent/workflows/brand-report.md +44 -0
  366. package/templates/.agent/workflows/create.md +59 -0
  367. package/templates/.agent/workflows/debug.md +103 -0
  368. package/templates/.agent/workflows/deploy.md +176 -0
  369. package/templates/.agent/workflows/enhance.md +63 -0
  370. package/templates/.agent/workflows/orchestrate.md +237 -0
  371. package/templates/.agent/workflows/plan.md +89 -0
  372. package/templates/.agent/workflows/preview.md +80 -0
  373. package/templates/.agent/workflows/report.md +49 -0
  374. package/templates/.agent/workflows/status.md +86 -0
  375. package/templates/.agent/workflows/test.md +144 -0
  376. package/templates/.agent/workflows/ui-ux-pro-max.md +231 -0
@@ -0,0 +1,4061 @@
1
+ # OpenXML SDK 3.x Complete Reference Encyclopedia
2
+
3
+ **Target:** DocumentFormat.OpenXml 3.x / .NET 8+ / C# 12
4
+ **Last Updated:** 2026-03-22
5
+
6
+ This document serves as an exhaustive reference for building DOCX files with the OpenXML SDK. Every code block is ready to copy-paste.
7
+
8
+ ---
9
+
10
+ ## Namespace Aliases Used Throughout
11
+
12
+ ```csharp
13
+ using DocumentFormat.OpenXml;
14
+ using DocumentFormat.OpenXml.Packaging;
15
+ using DocumentFormat.OpenXml.Wordprocessing;
16
+ ```
17
+
18
+ ---
19
+
20
+ ## Table of Contents
21
+
22
+ 1. [Document Creation Skeleton](#1-document-creation-skeleton)
23
+ 2. [Style System Deep Dive](#2-style-system-deep-dive)
24
+ 3. [Character Formatting (RunProperties)](#3-character-formatting-runproperties--exhaustive)
25
+ 4. [Paragraph Formatting (ParagraphProperties)](#4-paragraph-formatting-paragraphproperties--exhaustive)
26
+
27
+ ---
28
+
29
+ ## 1. Document Creation Skeleton
30
+
31
+ ### 1.1 Complete Flow: Create to Save
32
+
33
+ ```csharp
34
+ // =============================================================================
35
+ // DOCUMENT CREATION SKELETON
36
+ // =============================================================================
37
+ // This is the minimal complete flow for creating a valid DOCX from scratch.
38
+ // Follow these steps in order: Create -> AddParts -> AddContent -> Save.
39
+ //
40
+ // Key insight: WordprocessingDocument.Create() adds MainDocumentPart automatically,
41
+ // but all other parts (Styles, Settings, Numbering, Theme) must be added manually.
42
+
43
+ // --- STEP 1: CREATE THE PACKAGE ---
44
+ // The file path can be absolute or relative. WordprocessingDocumentType.Document
45
+ // is the standard choice for .docx files (vs. Template, MacroEnabled, etc.)
46
+ string outputPath = "C:\\Docs\\MyDocument.docx";
47
+
48
+ using var doc = WordprocessingDocument.Create(
49
+ outputPath, // File path
50
+ WordprocessingDocumentType.Document, // Document type enum
51
+ new DocumentOptions // Optional: AutoSave, etc.
52
+ {
53
+ AutoSave = false // true = flush changes automatically
54
+ });
55
+
56
+ // --- STEP 2: GET OR CREATE THE MAIN DOCUMENT PART ---
57
+ // When you call Create(), MainDocumentPart is automatically created and linked.
58
+ // You access it via .MainDocumentPart (not .AddMainDocumentPart, which would add
59
+ // a SECOND main part — illegal). For a fresh document, just use .MainDocumentPart.
60
+ var mainPart = doc.MainDocumentPart!;
61
+ var body = mainPart.Document.Body!; // Body is created automatically with the part
62
+
63
+ // --- STEP 3: ADD ADDITIONAL PARTS ---
64
+ // These are OPTIONAL but recommended for a complete document:
65
+ // - StyleDefinitionsPart: required for styles
66
+ // - NumberingDefinitionsPart: required for bullets/numbers
67
+ // - DocumentSettingsPart: zoom, proof state, tab stops, compatibility
68
+ // - ThemePart: color/theme information
69
+ // Parts are created fresh and linked via relationships.
70
+
71
+ // Example: Add styles part (covered in Section 2)
72
+ var stylesPart = mainPart.AddNewPart<StyleDefinitionsPart>();
73
+ stylesPart.Styles = new Styles();
74
+ stylesPart.Styles.Save();
75
+
76
+ // Example: Add settings part (covered in 1.4)
77
+ var settingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
78
+ settingsPart.Settings = new Settings();
79
+ settingsPart.Settings.Save();
80
+
81
+ // --- STEP 4: ADD CONTENT TO BODY ---
82
+ // Body accepts: Paragraph (w:p), Table (w:tbl), Structured Document Tag (w:sdt)
83
+ // Content is added in document order (no need for explicit index).
84
+ // IMPORTANT: SectionProperties (w:sectPr) MUST be the last child of body.
85
+ body.Append(new Paragraph(
86
+ new Run(new Text("Hello, World!"))));
87
+
88
+ // --- STEP 5: SET SECTION PROPERTIES (PAGE LAYOUT) ---
89
+ // sectPr defines page size, margins, headers/footers, columns, etc.
90
+ // It must be the last child of body. If missing, Word uses defaults (Letter/A4, 1" margins).
91
+ var sectPr = new SectionProperties();
92
+
93
+ // Page Size: Width/Height in DXA (1 inch = 1440 DXA)
94
+ // Letter: 12240 x 15840 DXA (8.5" x 11")
95
+ // A4: 11906 x 16838 DXA (210mm x 297mm)
96
+ sectPr.Append(new PageSize
97
+ {
98
+ Width = 12240u, // 8.5 inches
99
+ Height = 15840u // 11 inches
100
+ });
101
+
102
+ // Page Margins: all four margins in DXA
103
+ // Note: Top+Bottom margins + HeaderDistance = distance from page edge to text
104
+ sectPr.Append(new PageMargin
105
+ {
106
+ Top = 1440, // 1 inch
107
+ Bottom = 1440, // 1 inch
108
+ Left = 1440u, // 1 inch (uint required)
109
+ Right = 1440u, // 1 inch
110
+ Header = 720u, // 0.5 inch from page edge to header
111
+ Footer = 720u // 0.5 inch from page edge to footer
112
+ });
113
+
114
+ // Attach sectPr to body (must be last)
115
+ body.Append(sectPr);
116
+
117
+ // --- STEP 6: SAVE ---
118
+ // Because we use `using`, Dispose() is called automatically when the block exits.
119
+ // Dispose() saves the file. If you forget `using`, call doc.Save() explicitly.
120
+ ```
121
+
122
+ ### 1.2 Opening an Existing Document
123
+
124
+ ```csharp
125
+ // =============================================================================
126
+ // OPENING EXISTING DOCUMENTS
127
+ // =============================================================================
128
+ // Open() has multiple overloads:
129
+ // 1. Open(string path, bool isEditable, AutoSave)
130
+ // 2. Open(Stream, bool isEditable, AutoSave)
131
+ // 3. Open(string path, bool isEditable, OpenSettings)
132
+ //
133
+ // isEditable=true means open for read/write. false = read-only.
134
+ // isEditable=false is faster (shared locks avoided) but throws if file is read-only.
135
+
136
+ // --- OPEN FOR EDITING (READ/WRITE) ---
137
+ string inputPath = "C:\\Docs\\Existing.docx";
138
+ using var editDoc = WordprocessingDocument.Open(
139
+ inputPath,
140
+ isEditable: true, // Required for modification
141
+ new OpenSettings
142
+ {
143
+ AutoSave = true // Automatically save on Dispose
144
+ });
145
+
146
+ var body = editDoc.MainDocumentPart!.Document.Body!;
147
+ // ... make changes ...
148
+ // No explicit Save() needed if AutoSave = true
149
+
150
+ // --- OPEN AS READ-ONLY (FASTER) ---
151
+ using var readOnlyDoc = WordprocessingDocument.Open(
152
+ inputPath,
153
+ isEditable: false, // Read-only mode
154
+ new OpenSettings
155
+ {
156
+ // MarkupDeclarationProcess options
157
+ });
158
+
159
+ // --- OPEN FROM STREAM ---
160
+ byte[] fileBytes = File.ReadAllBytes(inputPath);
161
+ using var streamDoc = WordprocessingDocument.Open(
162
+ new MemoryStream(fileBytes),
163
+ isEditable: true,
164
+ new OpenSettings { AutoSave = false });
165
+
166
+ // After editing, you MUST copy the stream back to file if AutoSave=false:
167
+ // streamDoc.MainDocumentPart.Document.Save();
168
+ // File.WriteAllBytes(outputPath, streamStream.ToArray());
169
+
170
+ // --- OPEN FROM HTTP RESPONSE (WEB SCENARIO) ---
171
+ using var httpClient = new HttpClient();
172
+ var response = await httpClient.GetAsync("https://example.com/document.docx");
173
+ using var webStream = await response.Content.ReadAsStreamAsync();
174
+ using var webDoc = WordprocessingDocument.Open(webStream, isEditable: true);
175
+ ```
176
+
177
+ ### 1.3 Stream-Based Creation (MemoryStream for Web)
178
+
179
+ ```csharp
180
+ // =============================================================================
181
+ // STREAM-BASED DOCUMENT CREATION
182
+ // =============================================================================
183
+ // Use MemoryStream when you want to:
184
+ // 1. Generate a document in memory before sending to a client
185
+ // 2. Avoid touching the filesystem (ASP.NET Core scenarios)
186
+ // 3. Return a document from an API endpoint
187
+ //
188
+ // CRITICAL: The stream MUST be seekable when you call .Open().
189
+ // After WordprocessingDocument.Create(), the stream position is at the beginning.
190
+ // If you write to the stream BEFORE creating the document, seek to 0 first.
191
+
192
+ // --- CREATE IN MEMORY ---
193
+ MemoryStream memStream = new MemoryStream();
194
+
195
+ // Create directly on a stream (no file path involved)
196
+ using (var doc = WordprocessingDocument.Create(
197
+ memStream,
198
+ WordprocessingDocumentType.Document,
199
+ new DocumentOptions { AutoSave = false }))
200
+ {
201
+ var mainPart = doc.MainDocumentPart!;
202
+ mainPart.Document = new Document(new Body());
203
+ mainPart.Document.Body!.Append(new Paragraph(
204
+ new Run(new Text("Generated in memory"))));
205
+ mainPart.Document.Save(); // Save to the underlying stream
206
+ }
207
+ // At this point, memStream contains the complete DOCX
208
+
209
+ // --- SEND TO HTTP RESPONSE (ASP.NET Core) ---
210
+ // In an API controller:
211
+ [HttpGet("download")]
212
+ public async Task<IActionResult> DownloadDocument()
213
+ {
214
+ var memStream = new MemoryStream();
215
+
216
+ using (var doc = WordprocessingDocument.Create(
217
+ memStream,
218
+ WordprocessingDocumentType.Document))
219
+ {
220
+ var mainPart = doc.MainDocumentPart!;
221
+ mainPart.Document = new Document(new Body());
222
+ mainPart.Document.Body!.Append(new Paragraph(
223
+ new Run(new Text("Download me!"))));
224
+ mainPart.Document.Save();
225
+ }
226
+
227
+ memStream.Position = 0; // IMPORTANT: Reset position for reading
228
+ return File(memStream,
229
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
230
+ "GeneratedDocument.docx");
231
+ }
232
+
233
+ // --- CREATE FROM TEMPLATE IN MEMORY ---
234
+ // Useful for mail-merge style operations
235
+ MemoryStream templateStream = new MemoryStream();
236
+ File.WriteAllBytes("template.docx", templateStream.ToArray()); // Save a template first
237
+
238
+ using var templateSource = new MemoryStream(File.ReadAllBytes("template.docx"));
239
+ using var mergedDoc = (WordprocessingDocument)templateSource.Clone();
240
+
241
+ // Clone() creates an editable copy. Don't forget to set position:
242
+ mergedDoc.MainDocumentPart!.Document.Body!.Append(new Paragraph(
243
+ new Run(new Text("Added content"))));
244
+ ```
245
+
246
+ ### 1.4 Adding All Standard Parts
247
+
248
+ ```csharp
249
+ // =============================================================================
250
+ // ADDING ALL STANDARD DOCUMENT PARTS
251
+ // =============================================================================
252
+ // A complete document should have:
253
+ // 1. MainDocumentPart (auto-created)
254
+ // 2. StyleDefinitionsPart
255
+ // 3. NumberingDefinitionsPart
256
+ // 4. DocumentSettingsPart
257
+ // 5. ThemePart (optional)
258
+ // 6. Custom parts (headers, footers, comments, etc.)
259
+
260
+ // --- COMPLETE SETUP METHOD ---
261
+ public static void CreateCompleteDocument(string path)
262
+ {
263
+ using var doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);
264
+ var mainPart = doc.MainDocumentPart!;
265
+
266
+ // Initialize document
267
+ mainPart.Document = new Document(new Body());
268
+ var body = mainPart.Document.Body!;
269
+
270
+ // Add all parts
271
+ AddStylesPart(mainPart);
272
+ AddNumberingPart(mainPart);
273
+ AddSettingsPart(mainPart);
274
+ AddThemePart(mainPart);
275
+ AddHeadersAndFooters(mainPart);
276
+
277
+ // Add sample content
278
+ AddSampleContent(body);
279
+
280
+ // Section properties MUST be last
281
+ body.Append(CreateSectionProperties());
282
+
283
+ mainPart.Document.Save();
284
+ }
285
+
286
+ // --- STYLES PART ---
287
+ // See Section 2 for detailed style creation
288
+ private static void AddStylesPart(MainDocumentPart mainPart)
289
+ {
290
+ var stylesPart = mainPart.AddNewPart<StyleDefinitionsPart>();
291
+ var styles = new Styles();
292
+
293
+ // DocDefaults: document-wide defaults for run and paragraph properties
294
+ // These apply when no explicit style or direct formatting overrides them
295
+ styles.Append(new DocDefaults(
296
+ new RunPropertiesDefault(
297
+ new RunPropertiesBaseStyle(
298
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
299
+ new FontSize { Val = "22" }, // 22 half-points = 11pt
300
+ new FontSizeComplexScript { Val = "22" }
301
+ )
302
+ ),
303
+ new ParagraphPropertiesDefault(
304
+ new ParagraphPropertiesBaseStyle(
305
+ new SpacingBetweenLines { After = "200", Line = "276", LineRule = LineSpacingRuleValues.Auto }
306
+ )
307
+ )
308
+ ));
309
+
310
+ // Default Normal style
311
+ styles.Append(new Style(
312
+ new StyleName { Val = "Normal" },
313
+ new PrimaryStyle()
314
+ )
315
+ { Type = StyleValues.Paragraph, StyleId = "Normal", Default = true });
316
+
317
+ stylesPart.Styles = styles;
318
+ stylesPart.Styles.Save();
319
+ }
320
+
321
+ // --- NUMBERING PART ---
322
+ // Required for bulleted and numbered lists
323
+ private static void AddNumberingPart(MainDocumentPart mainPart)
324
+ {
325
+ var numberingPart = mainPart.AddNewPart<NumberingDefinitionsPart>();
326
+ var numbering = new Numbering();
327
+
328
+ // AbstractNum defines the list format (bullet, number, multilevel)
329
+ // Creates a bullet list definition with 3 levels
330
+ var abstractNum = new AbstractNum { AbstractNumberId = 1 };
331
+
332
+ // Level 0: Bullet (dot)
333
+ abstractNum.Append(new Level(
334
+ new StartNumberingValue { Val = 1 },
335
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
336
+ new LevelText { Val = "•" },
337
+ new LevelJustification { Val = LevelJustificationValues.Left },
338
+ new PreviousParagraphProperties(
339
+ new Indentation { Left = "720", Hanging = "360" }) // 720 DXA indent, 360 DXA hanging
340
+ )
341
+ { LevelIndex = 0 });
342
+
343
+ // Level 1: Dash
344
+ abstractNum.Append(new Level(
345
+ new StartNumberingValue { Val = 1 },
346
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
347
+ new LevelText { Val = "–" },
348
+ new LevelJustification { Val = LevelJustificationValues.Left },
349
+ new PreviousParagraphProperties(
350
+ new Indentation { Left = "1440", Hanging = "360" })
351
+ )
352
+ { LevelIndex = 1 });
353
+
354
+ // Level 2: Circle
355
+ abstractNum.Append(new Level(
356
+ new StartNumberingValue { Val = 1 },
357
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
358
+ new LevelText { Val = "◦" },
359
+ new LevelJustification { Val = LevelJustificationValues.Left },
360
+ new PreviousParagraphProperties(
361
+ new Indentation { Left = "2160", Hanging = "360" })
362
+ )
363
+ { LevelIndex = 2 });
364
+
365
+ numbering.Append(abstractNum);
366
+
367
+ // NumberingInstance links to AbstractNum and assigns a numId
368
+ numbering.Append(new NumberingInstance(
369
+ new AbstractNumId { Val = 1 }
370
+ )
371
+ { NumberID = 1 });
372
+
373
+ numberingPart.Numbering = numbering;
374
+ numberingPart.Numbering.Save();
375
+ }
376
+
377
+ // --- SETTINGS PART ---
378
+ // Contains document-level settings: zoom, proof state, default tab stop, etc.
379
+ private static void AddSettingsPart(MainDocumentPart mainPart)
380
+ {
381
+ var settingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
382
+ var settings = new Settings();
383
+
384
+ // Zoom: document zoom percentage (default 100%)
385
+ // Val is a percentage value (e.g., "100" = 100%)
386
+ settings.Append(new Zoom { Val = "100", Percent = true, SnapToGrid = true });
387
+
388
+ // ProofState: spelling/grammar check state
389
+ // Val combines bits: 1=grammar, 2=spelling, 3=both
390
+ settings.Append(new ProofState { Val = ProofingStateValues.Clean });
391
+
392
+ // Default tab stop interval in DXA
393
+ // Word inserts tab stops every 720 DXA (0.5 inch) by default
394
+ settings.Append(new DefaultTabStop { Val = 720 });
395
+
396
+ // Character spacing control: automatically adjust character spacing
397
+ // to maintain consistent line spacing (similar to InDesign)
398
+ settings.Append(new CharacterSpacingControl { Val = CharacterSpacingValues.CompressPunctuation });
399
+
400
+ // Compatibility settings: controls how Word handles certain formatting
401
+ // to ensure compatibility with different Word versions
402
+ settings.Append(new Compatibility(
403
+ new UseFELayout(), // Use formatted East Asian layout
404
+ new UseAsianDigraphicLineBreakRules(), // CJK line breaking rules
405
+ new AllowSpaceOfSameStyleInTable(), // Table cell spacing
406
+ new DoNotUseIndentAsPercentageForTabStops(), // Legacy tab behavior
407
+ new ProportionalOtherIndents(), // Proportional indents
408
+ new LayoutTableRawTextInTable() // Raw text in layout tables
409
+ ));
410
+
411
+ // Revision tracking view settings
412
+ settings.Append(new RevisionView { DocPart = false, Formatting = true, Ink = true, Markup = true });
413
+
414
+ settingsPart.Settings = settings;
415
+ settingsPart.Settings.Save();
416
+ }
417
+
418
+ // --- THEME PART ---
419
+ // Defines color scheme, font scheme, and format scheme for the document theme
420
+ private static void AddThemePart(MainDocumentPart mainPart)
421
+ {
422
+ var themePart = mainPart.AddNewPart<ThemePart>();
423
+ var theme = new Theme(
424
+ new ThemeElements(
425
+ // Color scheme: 10 predefined theme colors
426
+ new ColorScheme(
427
+ new Dark1Color(new Color { Val = "000000" }),
428
+ new Light1Color(new Color { Val = "FFFFFF" }),
429
+ new Dark2Color(new Color { Val = "1F497D" }),
430
+ new Light2Color(new Color { Val = "EEECE1" }),
431
+ new Accent1Color(new Color { Val = "4F81BD" }),
432
+ new Accent2Color(new Color { Val = "C0504D" }),
433
+ new Accent3Color(new Color { Val = "9BBB59" }),
434
+ new Accent4Color(new Color { Val = "8064A2" }),
435
+ new Accent5Color(new Color { Val = "4BACC6" }),
436
+ new Accent6Color(new Color { Val = "F79646" }),
437
+ new Hyperlink(new Color { Val = "0000FF" }),
438
+ new FollowedHyperlinkColor(new Color { Val = "800080" })
439
+ ),
440
+ // Font scheme: major (headings) and minor (body) fonts
441
+ new FontScheme(
442
+ new MajorFont { Val = "Calibri Light" },
443
+ new MinorFont { Val = "Calibri" }
444
+ ),
445
+ // Format scheme: default fill and effect styles
446
+ new FormatScheme(
447
+ new FillStyleList(
448
+ new FillStyle { Fill = new PatternFill { PatternType = PatternValues.Solid } }
449
+ ),
450
+ new LineStyleList(
451
+ new LineStyle { Val = LineValues.Single }
452
+ )
453
+ )
454
+ ),
455
+ new ThemeName { Val = "Office Theme" },
456
+ new ThemeNames(
457
+ new LanguageBasedString { Val = "en-US", LanguageId = "x-none" }
458
+ )
459
+ );
460
+
461
+ themePart.Theme = theme;
462
+ themePart.Theme.Save();
463
+ }
464
+
465
+ // --- HEADERS AND FOOTERS ---
466
+ private static void AddHeadersAndFooters(MainDocumentPart mainPart)
467
+ {
468
+ // Header
469
+ var headerPart = mainPart.AddNewPart<HeaderPart>();
470
+ headerPart.Header = new Header(
471
+ new Paragraph(
472
+ new ParagraphProperties(
473
+ new Justification { Val = JustificationValues.Right }),
474
+ new Run(
475
+ new RunProperties(
476
+ new RunFonts { Ascii = "Calibri Light", HighAnsi = "Calibri Light" },
477
+ new Italic(),
478
+ new FontSize { Val = "20" } // 10pt
479
+ ),
480
+ new Text("Document Header"))
481
+ ));
482
+ var headerId = mainPart.GetIdOfPart(headerPart);
483
+
484
+ // Footer
485
+ var footerPart = mainPart.AddNewPart<FooterPart>();
486
+ footerPart.Footer = new Footer(
487
+ new Paragraph(
488
+ new ParagraphProperties(
489
+ new Justification { Val = JustificationValues.Center }),
490
+ new Run(new Text("Page ") { Space = SpaceProcessingModeValues.Preserve }),
491
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
492
+ new Run(new FieldCode(" PAGE ") { Space = SpaceProcessingModeValues.Preserve }),
493
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End }),
494
+ new Run(new Text(" of ") { Space = SpaceProcessingModeValues.Preserve }),
495
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
496
+ new Run(new FieldCode(" NUMPAGES ") { Space = SpaceProcessingModeValues.Preserve }),
497
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End })
498
+ ));
499
+ var footerId = mainPart.GetIdOfPart(footerPart);
500
+
501
+ // Reference IDs in section properties
502
+ // (added in CreateSectionProperties below)
503
+ }
504
+
505
+ // --- SECTION PROPERTIES (COMPLETE) ---
506
+ private static SectionProperties CreateSectionProperties()
507
+ {
508
+ var sectPr = new SectionProperties();
509
+
510
+ // Header/Footer references (must come before page size/margins)
511
+ var mainPart = doc.MainDocumentPart; // Note: in real code, pass as parameter
512
+ sectPr.Append(new HeaderReference
513
+ {
514
+ Type = HeaderFooterValues.Default,
515
+ Id = mainPart!.GetIdOfPart(mainPart.HeaderParts.First())
516
+ });
517
+ sectPr.Append(new FooterReference
518
+ {
519
+ Type = HeaderFooterValues.Default,
520
+ Id = mainPart.GetIdOfPart(mainPart.FooterParts.First())
521
+ });
522
+
523
+ // Page size
524
+ sectPr.Append(new PageSize { Width = 12240u, Height = 15840u });
525
+
526
+ // Page margins
527
+ sectPr.Append(new PageMargin
528
+ {
529
+ Top = 1440,
530
+ Bottom = 1440,
531
+ Left = 1440u,
532
+ Right = 1440u,
533
+ Header = 720u,
534
+ Footer = 720u
535
+ });
536
+
537
+ // Page numbering format
538
+ sectPr.Append(new PageNumberType { Start = 1, Format = NumberFormatValues.Decimal });
539
+
540
+ // Column settings (default: 1 column)
541
+ sectPr.Append(new Columns { ColumnCount = 1, EqualWidth = true });
542
+
543
+ // Paper source (printer tray)
544
+ // sectPr.Append(new PaperSource { Tray = 1, Paper = 7 });
545
+
546
+ return sectPr;
547
+ }
548
+ ```
549
+
550
+ ### 1.5 Unit Systems Reference
551
+
552
+ ```csharp
553
+ // =============================================================================
554
+ // UNIT SYSTEMS IN OPENXML
555
+ // =============================================================================
556
+ // Understanding units is critical. Wrong unit = wrong formatting.
557
+ //
558
+ // DXA (Twentieths of a DXA) - "Standard Document Unit"
559
+ // 1 DXA = 1/20th of a point
560
+ // 1 inch = 1440 DXA
561
+ // 1 cm = 567 DXA (approx)
562
+ // Used for: margins, indents, spacing, tab stops, column widths
563
+ //
564
+ // Half-Points (sz) - Font Size
565
+ // Value is in half-points (1/2 point increments)
566
+ // 24 = 12pt, 28 = 14pt, 36 = 18pt, 48 = 24pt
567
+ // Used for: FontSize.Val, FontSizeComplexScript.Val
568
+ //
569
+ // Points (pt) - Direct Measurements
570
+ // Standard typographic point (72 per inch)
571
+ // Used for: some line spacing values, border widths
572
+ //
573
+ // EMU (English Metric Units) - Drawing Objects
574
+ // 1 inch = 914400 EMU
575
+ // Used for: drawing object sizes, shapes, images
576
+ //
577
+ // STARS (Special Twips Advanced Right-Left) - CJK Indentation
578
+ // Used for: FirstLineChars, HangingChars (special FirstLine/Hanging for CJK)
579
+ // Converts character counts to DXA based on font metrics
580
+ //
581
+ // LINE SPACING SPECIAL VALUES:
582
+ // Line = "240" with LineRule = Auto = single spacing (default)
583
+ // Line = "480" with LineRule = Auto = double spacing
584
+ // Line = "360" with LineRule = Auto = 1.5 spacing
585
+ // Line = "240" with LineRule = Exact = exactly 12pt
586
+ // Line = "288" with LineRule = AtLeast = at least 14.4pt (grows with content)
587
+
588
+ // --- CONVERSION HELPER METHODS ---
589
+ public static class OpenXmlUnits
590
+ {
591
+ // DXA conversions
592
+ public static int InchesToDxa(double inches) => (int)(inches * 1440);
593
+ public static int CmToDxa(double cm) => (int)(cm * 567.0);
594
+ public static int PtToDxa(double pt) => (int)(pt * 20);
595
+ public static double DxaToInches(int dxa) => dxa / 1440.0;
596
+ public static double DxaToCm(int dxa) => dxa / 567.0;
597
+ public static double DxaToPt(int dxa) => dxa / 20.0;
598
+
599
+ // EMU conversions (for drawings)
600
+ public static long InchesToEmu(double inches) => (long)(inches * 914400);
601
+ public static long CmToEmu(double cm) => (long)(cm * 360000);
602
+ public static double EmuToInches(long emu) => emu / 914400.0;
603
+
604
+ // Half-point conversions (font sizes)
605
+ public static int PtToHalfPt(double pt) => (int)(pt * 2);
606
+ public static int FontSizeToSz(double ptSize) => (int)(ptSize * 2);
607
+ public static double SzToPt(int sz) => sz / 2.0;
608
+
609
+ // Line spacing
610
+ public static int SingleSpacing => 240;
611
+ public static int DoubleSpacing => 480;
612
+ public static int OneAndHalfSpacing => 360;
613
+ public static int LineSpacingPt(double pt) => (int)(pt * 20); // Convert to DXA
614
+ }
615
+
616
+ // Example usage:
617
+ var marginInInches = OpenXmlUnits.DxaToInches(1440); // 1.0
618
+ var fontSizeInSz = OpenXmlUnits.FontSizeToSz(12.0); // 24
619
+ var indentInDxa = OpenXmlUnits.InchesToDxa(0.5); // 720
620
+ ```
621
+
622
+ ---
623
+
624
+ ## 2. Style System Deep Dive
625
+
626
+ ### 2.1 Style Types and Structure
627
+
628
+ ```csharp
629
+ // =============================================================================
630
+ // STYLE TYPES OVERVIEW
631
+ // =============================================================================
632
+ // OpenXML defines 4 style types (StyleValues enum):
633
+ // 1. Paragraph (w:p) - controls paragraph-level formatting
634
+ // 2. Character (w:r) - controls inline/run-level formatting
635
+ // 3. Table (w:tbl) - controls table-level formatting
636
+ // 4. Numbering (w:num) - NOT a style type, but a separate numbering system
637
+ //
638
+ // Key insight: A style can be BOTH paragraph and character style (linked style).
639
+ // The "linkedStyle" element links a paragraph style to a character style.
640
+
641
+ // --- MINIMAL PARAGRAPH STYLE ---
642
+ // A paragraph style controls: pPr (paragraph properties) and optionally rPr
643
+ Style minimalParaStyle = new Style(
644
+ new StyleName { Val = "MyParagraphStyle" },
645
+ new PrimaryStyle() // Primary styles appear in Style gallery
646
+ )
647
+ {
648
+ Type = StyleValues.Paragraph,
649
+ StyleId = "MyParagraphStyle"
650
+ };
651
+
652
+ // --- MINIMAL CHARACTER STYLE ---
653
+ // A character style controls: rPr only (no pPr)
654
+ Style minimalCharStyle = new Style(
655
+ new StyleName { Val = "MyCharacterStyle" },
656
+ new PrimaryStyle()
657
+ )
658
+ {
659
+ Type = StyleValues.Character,
660
+ StyleId = "MyCharacterStyle"
661
+ };
662
+
663
+ // Character style with run properties (fonts, size, bold, etc.)
664
+ Style charStyleWithFormatting = new Style(
665
+ new StyleName { Val = "Emphasis" },
666
+ new PrimaryStyle(),
667
+ new StyleRunProperties(
668
+ new Italic(),
669
+ new Color { Val = "C00000" } // Dark red
670
+ )
671
+ )
672
+ {
673
+ Type = StyleValues.Character,
674
+ StyleId = "Emphasis"
675
+ };
676
+
677
+ // --- LINKED STYLE (Paragraph + Character) ---
678
+ // A linked style combines both: it can be applied to a paragraph OR a run.
679
+ // This is how Word's "Heading 1" works — applies to paragraphs, but you can
680
+ // also select text within a heading and apply the same style as character formatting.
681
+ Style linkedStyle = new Style(
682
+ new StyleName { Val = "LinkedStyle" },
683
+ new PrimaryStyle(),
684
+ new LinkedStyle { Val = "LinkedStyleChar" }, // Links to character style
685
+ new StyleParagraphProperties(
686
+ new SpacingBetweenLines { After = "120" }
687
+ ),
688
+ new StyleRunProperties(
689
+ new Bold(),
690
+ new FontSize { Val = "24" }
691
+ )
692
+ )
693
+ {
694
+ Type = StyleValues.Paragraph,
695
+ StyleId = "LinkedStyle"
696
+ };
697
+
698
+ // Corresponding character style (normally same name + "Char" suffix by convention)
699
+ Style linkedStyleChar = new Style(
700
+ new StyleName { Val = "LinkedStyle Char" }, // Word convention: adds " Char"
701
+ new PrimaryStyle(),
702
+ new StyleRunProperties(
703
+ new Bold(),
704
+ new FontSize { Val = "24" }
705
+ )
706
+ )
707
+ {
708
+ Type = StyleValues.Character,
709
+ StyleId = "LinkedStyleChar"
710
+ };
711
+
712
+ // --- TABLE STYLE ---
713
+ Style tableStyle = new Style(
714
+ new StyleName { Val = "MyTableStyle" },
715
+ new PrimaryStyle(),
716
+ new StyleTableProperties(
717
+ new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct }, // 50% width
718
+ new TableBorders(
719
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
720
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
721
+ new LeftBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
722
+ new RightBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
723
+ new InsideHorizontalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" },
724
+ new InsideVerticalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" }
725
+ ),
726
+ new TableCellMarginDefault(
727
+ new TopMargin { Width = "0", Type = TableWidthUnitValues.DXA },
728
+ new StartMargin { Width = "108", Type = TableWidthUnitValues.DXA },
729
+ new BottomMargin { Width = "0", Type = TableWidthUnitValues.DXA },
730
+ new EndMargin { Width = "108", Type = TableWidthUnitValues.DXA }
731
+ )
732
+ )
733
+ )
734
+ {
735
+ Type = StyleValues.Table,
736
+ StyleId = "MyTableStyle"
737
+ };
738
+ ```
739
+
740
+ ### 2.2 DocDefaults and Document-Wide Defaults
741
+
742
+ ```csharp
743
+ // =============================================================================
744
+ // DOCDEFAULTS: DOCUMENT-WIDE DEFAULTS
745
+ // =============================================================================
746
+ // DocDefaults lives inside Styles and provides fallback values when:
747
+ // 1. No explicit style is applied
748
+ // 2. No direct formatting is applied
749
+ // It contains RunPropertiesDefault and/or ParagraphPropertiesDefault.
750
+ //
751
+ // CRITICAL: DocDefaults applies to the entire document. Any explicit style
752
+ // or direct formatting will override it.
753
+
754
+ // --- COMPLETE DOCDEFAULTS SETUP ---
755
+ var docDefaults = new DocDefaults(
756
+ // Run properties defaults: default font, size, language for all runs
757
+ new RunPropertiesDefault(
758
+ new RunPropertiesBaseStyle(
759
+ // RunFonts: which font to use for each script
760
+ // Word will fall back through these: ASCII -> HighAnsi -> EastAsia -> ComplexScript
761
+ // Always specify at minimum Ascii and HighAnsi
762
+ new RunFonts
763
+ {
764
+ Ascii = "Calibri", // Western/Latin font (primary)
765
+ HighAnsi = "Calibri", // Latin characters (often same as Ascii)
766
+ EastAsia = "SimSun", // East Asian font (CJK)
767
+ ComplexScript = "Arial", // Complex scripts (Arabic, Hebrew, Thai)
768
+ ASCIITheme = ThemeFontValues.Minor,
769
+ HighAnsiTheme = ThemeFontValues.Minor,
770
+ EastAsiaTheme = ThemeFontValues.Minor,
771
+ ComplexScriptTheme = ThemeFontValues.Minor
772
+ },
773
+ // FontSize: in HALF-POINTS (24 = 12pt, 22 = 11pt, 20 = 10pt)
774
+ new FontSize { Val = "22" }, // 11pt for body
775
+ new FontSizeComplexScript { Val = "22" },
776
+ // Languages: required for proper hyphenation and spell checking
777
+ new Languages { Val = "en-US" }, // Default language
778
+ new Languages { EastAsia = "zh-CN", Val = "en-US" } // Can set multiple
779
+ )
780
+ ),
781
+ // Paragraph properties defaults: default spacing, etc.
782
+ new ParagraphPropertiesDefault(
783
+ new ParagraphPropertiesBaseStyle(
784
+ // SpacingBetweenLines: default paragraph spacing
785
+ // After = "200" = 200 DXA = 10pt after each paragraph
786
+ new SpacingBetweenLines
787
+ {
788
+ After = "200",
789
+ Line = "276",
790
+ LineRule = LineSpacingRuleValues.Auto // Auto = 1.15x line height
791
+ }
792
+ )
793
+ )
794
+ );
795
+
796
+ // --- LAYOUT LUNCTIONS (LATENT STYLES) ---
797
+ // Latent styles are hidden styles that exist in Word but aren't in styles.xml.
798
+ // They provide fast-access defaults for formatting (e.g., Normal, Heading 1-6, etc.)
799
+ // when the user hasn't explicitly customized them.
800
+ //
801
+ // DocDefaults can define LatentStyleCountOverride to adjust count,
802
+ // but true latent styles are controlled by Normal.dotm (Word's global template).
803
+ Styles CreateStylesWithDocDefaults()
804
+ {
805
+ var styles = new Styles();
806
+
807
+ // DocDefaults with run and paragraph properties defaults
808
+ styles.Append(new DocDefaults(
809
+ new RunPropertiesDefault(
810
+ new RunPropertiesBaseStyle(
811
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
812
+ new FontSize { Val = "22" },
813
+ new Languages { Val = "en-US" }
814
+ )
815
+ ),
816
+ new ParagraphPropertiesDefault(
817
+ new ParagraphPropertiesBaseStyle(
818
+ new SpacingBetweenLines { After = "160", Line = "276", LineRule = LineSpacingRuleValues.Auto }
819
+ )
820
+ )
821
+ ));
822
+
823
+ // LatentStyles: override defaults for built-in latent styles
824
+ // These control Word's "fast-styles" like Heading 1-6 before they're customized
825
+ styles.Append(new LatentStyles(
826
+ new Count { Val = 159 }, // Total latent style count
827
+ new FirstLineChars { Val = 352 }, // Default first line char count
828
+ new HorizontalOverflow { Val = HorizontalOverflowValues.Overflow },
829
+ new VerticalOverflow { Val = VerticalOverflowValues.Overflow },
830
+ new KoreanSpaceAdjust { Val = true },
831
+ // Each LatentStyleException overrides ONE attribute of ONE latent style
832
+ // StyleID = the built-in style name (e.g., "Normal", "heading 1")
833
+ // Attribute: what to change (bold, italic, font, color, etc.)
834
+ // The defaults for built-in headings: font=Calibri, size=24, bold
835
+ new LatentStyleException(
836
+ new Primary烙,
837
+ new StyleName { Val = "Normal" },
838
+ new UIPriority { Val = 1 },
839
+ new PrimaryZone(),
840
+ new QuickStyle()
841
+ ),
842
+ new LatentStyleException(
843
+ new Primary烙,
844
+ new StyleName { Val = "heading 1" },
845
+ new UIPriority { Val = 9 },
846
+ new PrimaryZone(),
847
+ new QuickStyle(),
848
+ new Bold(),
849
+ new BoldComplexScript(),
850
+ new FontSize { Val = "48" }, // 24pt = 48 half-pts
851
+ new FontSizeComplexScript { Val = "48" }
852
+ )
853
+ ));
854
+
855
+ return styles;
856
+ }
857
+ ```
858
+
859
+ ### 2.3 Complete Heading Styles Hierarchy
860
+
861
+ ```csharp
862
+ // =============================================================================
863
+ // HEADING STYLES WITH PROPER INHERITANCE CHAIN
864
+ // =============================================================================
865
+ // Word's built-in heading system uses style inheritance:
866
+ // Normal (base) -> Heading1 -> Heading2 -> Heading3 -> Heading4 -> Heading5 -> Heading6
867
+ //
868
+ // Why this matters:
869
+ // - Each heading INHERITS from its parent (basedOn)
870
+ // - Define common properties in Normal, override in each heading
871
+ // - Change body font once in Normal, all headings inherit it
872
+ // - Heading-specific properties override as needed
873
+
874
+ // --- HEADING STYLE FACTORY ---
875
+ public static Style CreateHeadingStyle(int level, FontConfig fonts)
876
+ {
877
+ // Validate level (1-9 are valid, 1-6 are standard)
878
+ if (level < 1 || level > 9)
879
+ throw new ArgumentOutOfRangeException(nameof(level));
880
+
881
+ double[] headingSizes = [26.0, 20.0, 16.0, 14.0, 12.0, 11.0, 11.0, 11.0, 11.0];
882
+ string[] outlineLevels = ["0", "1", "2", "3", "4", "5", "6", "7", "8"};
883
+
884
+ var style = new Style(
885
+ new StyleName { Val = $"heading {level}" }, // Display name
886
+ new BasedOn { Val = level == 1 ? "Normal" : $"Heading{level - 1}" }, // Parent style
887
+ new NextParagraphStyle { Val = "Normal" }, // After heading -> Normal
888
+ new PrimaryStyle(), // Show in Styles gallery
889
+ new UIPriority { Val = 9 - level }, // Priority in gallery (H1 = 8, H2 = 7, etc.)
890
+ new QuickStyle(), // Appears in Quick Styles gallery
891
+ // Paragraph properties: spacing, keep options, outline level
892
+ new StyleParagraphProperties(
893
+ new KeepNext(), // Keep heading with next paragraph
894
+ new KeepLines(), // Keep all lines of heading together
895
+ new SpacingBetweenLines // Spacing before/after
896
+ {
897
+ Before = level == 1 ? "480" : "240", // H1 = 240pt before, others = 120pt
898
+ After = "120"
899
+ },
900
+ new OutlineLevel { Val = level - 1 } // 0-indexed for H1=0, H2=1, etc.
901
+ ),
902
+ // Run properties: font, size, bold
903
+ new StyleRunProperties(
904
+ new RunFonts
905
+ {
906
+ Ascii = fonts.HeadingFont,
907
+ HighAnsi = fonts.HeadingFont,
908
+ EastAsia = "SimHei" // Bold heading font for CJK
909
+ },
910
+ new FontSize { Val = UnitConverter.FontSizeToSz(headingSizes[level - 1]) },
911
+ new FontSizeComplexScript { Val = UnitConverter.FontSizeToSz(headingSizes[level - 1]) },
912
+ new Bold(),
913
+ new BoldComplexScript()
914
+ )
915
+ )
916
+ {
917
+ Type = StyleValues.Paragraph,
918
+ StyleId = $"Heading{level}"
919
+ };
920
+
921
+ return style;
922
+ }
923
+
924
+ // --- ADD ALL HEADING STYLES TO STYLES COLLECTION ---
925
+ public static void AddHeadingStyles(Styles styles, FontConfig fonts)
926
+ {
927
+ for (int i = 1; i <= 6; i++)
928
+ {
929
+ styles.Append(CreateHeadingStyle(i, fonts));
930
+ }
931
+
932
+ // Also add Heading 7-9 (valid in Word, less commonly used)
933
+ for (int i = 7; i <= 9; i++)
934
+ {
935
+ styles.Append(CreateHeadingStyle(i, fonts));
936
+ }
937
+ }
938
+
939
+ // --- HEADING STYLES INHERITANCE VISUALIZATION ---
940
+ // When you apply "Heading2" (basedOn="Heading1"):
941
+ //
942
+ // Normal style:
943
+ // - Font: Calibri 11pt
944
+ // - Spacing: 0 before, 200 after
945
+ // - No bold
946
+ //
947
+ // Heading1 (basedOn="Normal"):
948
+ // - Inherits: Calibri 11pt
949
+ // - Overrides: Calibri Light 26pt, Bold, Spacing 480 before/120 after
950
+ // - Adds: KeepNext, KeepLines, OutlineLevel=0
951
+ //
952
+ // Heading2 (basedOn="Heading1"):
953
+ // - Inherits: Calibri Light 26pt, Bold, KeepNext, KeepLines
954
+ // - Overrides: 20pt
955
+ // - Inherits: OutlineLevel=1
956
+ //
957
+ // Effective result: Heading2 = Calibri Light 20pt Bold, KeepNext+KeepLines, 480/120 spacing, OL=1
958
+ ```
959
+
960
+ ### 2.4 Style Inheritance Chain Resolution
961
+
962
+ ```csharp
963
+ // =============================================================================
964
+ // STYLE INHERITANCE RESOLUTION
965
+ // =============================================================================
966
+ // OpenXML styles resolve properties through the basedOn chain at RENDER TIME.
967
+ // The document.xml stores only the styleId, not the resolved properties.
968
+ // Word (or this library) walks the chain at load/display time.
969
+ //
970
+ // Example: Applying "Heading2" to a paragraph
971
+ //
972
+ // 1. Start with Heading2 style definition
973
+ // 2. Walk basedOn chain: Heading2 -> Heading1 -> Normal -> (null)
974
+ // 3. Collect properties in reverse order (most generic first):
975
+ // a. Normal: Ascii=Calibri, sz=22, no bold
976
+ // b. Heading1: Ascii=Calibri Light, sz=48, bold (override Calibri, sz, bold)
977
+ // c. Heading2: sz=40 (override sz only)
978
+ // 4. Final resolved style: Ascii=Calibri Light, sz=40, bold (bold from H1)
979
+ //
980
+ // IMPORTANT: Style override is COMPLETE for each element type:
981
+ // - If Normal has rPr with Fonts, and Heading1 has pPr only,
982
+ // Heading1 still inherits Normal's rPr fully.
983
+ // - StyleRunProperties (rPr) and StyleParagraphProperties (pPr) are separate.
984
+
985
+ // --- RESOLVING STYLE PROPERTIES MANUALLY ---
986
+ // For debugging or custom rendering, you may need to resolve style chains
987
+ public static class StyleResolver
988
+ {
989
+ public record ResolvedStyle(
990
+ StyleName? Name,
991
+ RunProperties? RunProps,
992
+ ParagraphProperties? ParaProps,
993
+ string? BasedOn,
994
+ string Type);
995
+
996
+ public static ResolvedStyle Resolve(Styles styles, string styleId)
997
+ {
998
+ var styleMap = styles.Elements<Style>().ToDictionary(s => s.StyleId?.Value ?? "");
999
+
1000
+ var resolvedRpr = new List<RunProperties>();
1001
+ var resolvedPpr = new List<ParagraphProperties>();
1002
+ string? currentId = styleId;
1003
+ string? name = null;
1004
+ string type = "paragraph";
1005
+
1006
+ // Walk the chain
1007
+ while (currentId != null && styleMap.TryGetValue(currentId, out var style))
1008
+ {
1009
+ name ??= style.Name?.Val?.Value;
1010
+ type = style.Type?.Value?.ToString() ?? "paragraph";
1011
+
1012
+ // Collect rPr (style-level run properties)
1013
+ var rpr = style.StyleRunProperties;
1014
+ if (rpr != null) resolvedRpr.Add(rpr);
1015
+
1016
+ // Collect pPr (style-level paragraph properties)
1017
+ var ppr = style.StyleParagraphProperties;
1018
+ if (ppr != null) resolvedPpr.Add(ppr);
1019
+
1020
+ // Move to parent
1021
+ currentId = style.BasedOn?.Val?.Value;
1022
+ }
1023
+
1024
+ // Merge in reverse order (base styles first, derived last)
1025
+ // This is a simplified merge — real Word merging is more complex
1026
+ var mergedRpr = MergeRunProperties(resolvedRpr);
1027
+ var mergedPpr = MergeParagraphProperties(resolvedPpr);
1028
+
1029
+ return new ResolvedStyle(
1030
+ name != null ? new StyleName { Val = name } : null,
1031
+ mergedRpr,
1032
+ mergedPpr,
1033
+ styleId,
1034
+ type);
1035
+ }
1036
+
1037
+ private static RunProperties MergeRunProperties(List<RunProperties> chain)
1038
+ {
1039
+ var merged = new RunProperties();
1040
+ // In real implementation, copy each child element from chain[0] first,
1041
+ // then chain[1], etc., overriding as you go
1042
+ foreach (var rpr in chain)
1043
+ {
1044
+ foreach (var child in rpr.ChildElements)
1045
+ {
1046
+ // Skip duplicates, keep derived class's version
1047
+ merged.RemoveAll(child.GetType());
1048
+ merged.Append(child.CloneNode(true));
1049
+ }
1050
+ }
1051
+ return merged;
1052
+ }
1053
+
1054
+ private static ParagraphProperties MergeParagraphProperties(List<ParagraphProperties> chain)
1055
+ {
1056
+ var merged = new ParagraphProperties();
1057
+ foreach (var ppr in chain)
1058
+ {
1059
+ foreach (var child in ppr.ChildElements)
1060
+ {
1061
+ merged.RemoveAll(child.GetType());
1062
+ merged.Append(child.CloneNode(true));
1063
+ }
1064
+ }
1065
+ return merged;
1066
+ }
1067
+ }
1068
+
1069
+ // --- STYLE ID VS STYLE NAME ---
1070
+ // StyleId: the machine-readable identifier (used in w:pStyle val="Heading1")
1071
+ // StyleName.Val: the display name shown in Word UI ("Heading 1")
1072
+ //
1073
+ // Word allows StyleId="Heading1" with StyleName.Val="Custom Heading One"
1074
+ // The Id must be unique within the document; the Name can duplicate others.
1075
+ //
1076
+ // Built-in styles use specific Ids:
1077
+ // "Normal", "Heading1"-"Heading9", "Title", "Subtitle", "Quote", "Quote1",
1078
+ // "IntenseQuote", "SubtleReference", "Bibliography", "TOC1"-"TOC9", etc.
1079
+ ```
1080
+
1081
+ ### 2.5 Complete Style Definitions Example
1082
+
1083
+ ```csharp
1084
+ // =============================================================================
1085
+ // COMPLETE STYLE DEFINITIONS FOR A BUSINESS DOCUMENT
1086
+ // =============================================================================
1087
+ // This creates a complete styles.xml with all recommended styles for a
1088
+ // professional document: Normal, Title, Subtitle, Headings 1-6, Quote,
1089
+ // IntenseQuote, and linked character styles.
1090
+
1091
+ public static Styles CreateBusinessDocumentStyles()
1092
+ {
1093
+ var styles = new Styles();
1094
+
1095
+ // --- DOCDEFAULTS ---
1096
+ styles.Append(new DocDefaults(
1097
+ new RunPropertiesDefault(
1098
+ new RunPropertiesBaseStyle(
1099
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
1100
+ new FontSize { Val = "22" },
1101
+ new FontSizeComplexScript { Val = "22" },
1102
+ new Languages { Val = "en-US" }
1103
+ )
1104
+ ),
1105
+ new ParagraphPropertiesDefault(
1106
+ new ParagraphPropertiesBaseStyle(
1107
+ new SpacingBetweenLines { After = "200", Line = "276", LineRule = LineSpacingRuleValues.Auto }
1108
+ )
1109
+ )
1110
+ ));
1111
+
1112
+ // --- NORMAL STYLE (BASE FOR ALL) ---
1113
+ styles.Append(new Style(
1114
+ new StyleName { Val = "Normal" },
1115
+ new PrimaryStyle(),
1116
+ new UIPriority { Val = 10 },
1117
+ new Primary烙,
1118
+ new StyleRunProperties(
1119
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
1120
+ new FontSize { Val = "22" },
1121
+ new FontSizeComplexScript { Val = "22" }
1122
+ )
1123
+ )
1124
+ { Type = StyleValues.Paragraph, StyleId = "Normal", Default = true });
1125
+
1126
+ // --- TITLE STYLE ---
1127
+ styles.Append(new Style(
1128
+ new StyleName { Val = "Title" },
1129
+ new BasedOn { Val = "Normal" },
1130
+ new NextParagraphStyle { Val = "Normal" },
1131
+ new PrimaryStyle(),
1132
+ new UIPriority { Val = 1 },
1133
+ new QuickStyle(),
1134
+ new StyleParagraphProperties(
1135
+ new Justification { Val = JustificationValues.Center },
1136
+ new SpacingBetweenLines { After = "300", Line = "240", LineRule = LineSpacingRuleValues.Auto },
1137
+ new KeepNext(),
1138
+ new KeepLines()
1139
+ ),
1140
+ new StyleRunProperties(
1141
+ new RunFonts { Ascii = "Calibri Light", HighAnsi = "Calibri Light" },
1142
+ new FontSize { Val = "56" }, // 28pt
1143
+ new FontSizeComplexScript { Val = "56" },
1144
+ new Bold(),
1145
+ new BoldComplexScript(),
1146
+ new Color { Val = "1F497D" } // Dark blue
1147
+ )
1148
+ )
1149
+ { Type = StyleValues.Paragraph, StyleId = "Title" });
1150
+
1151
+ // --- SUBTITLE STYLE ---
1152
+ styles.Append(new Style(
1153
+ new StyleName { Val = "Subtitle" },
1154
+ new BasedOn { Val = "Normal" },
1155
+ new NextParagraphStyle { Val = "Normal" },
1156
+ new PrimaryStyle(),
1157
+ new UIPriority { Val = 2 },
1158
+ new QuickStyle(),
1159
+ new StyleParagraphProperties(
1160
+ new Justification { Val = JustificationValues.Center },
1161
+ new SpacingBetweenLines { After = "200" },
1162
+ new KeepNext(),
1163
+ new KeepLines()
1164
+ ),
1165
+ new StyleRunProperties(
1166
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
1167
+ new FontSize { Val = "26" }, // 13pt
1168
+ new Color { Val = "5A5A5A" } // Gray
1169
+ )
1170
+ )
1171
+ { Type = StyleValues.Paragraph, StyleId = "Subtitle" });
1172
+
1173
+ // --- HEADING 1-6 STYLES ---
1174
+ AddHeadingStyles(styles);
1175
+
1176
+ // --- QUOTE STYLES ---
1177
+ // Quote (indented, italic)
1178
+ styles.Append(new Style(
1179
+ new StyleName { Val = "Quote" },
1180
+ new BasedOn { Val = "Normal" },
1181
+ new NextParagraphStyle { Val = "Normal" },
1182
+ new PrimaryStyle(),
1183
+ new UIPriority { Val = 29 },
1184
+ new QuickStyle(),
1185
+ new StyleParagraphProperties(
1186
+ new Justification { Val = JustificationValues.Both },
1187
+ new Indentation { Left = "720", Right = "720" },
1188
+ new SpacingBetweenLines { After = "160" },
1189
+ new KeepNext(),
1190
+ new KeepLines()
1191
+ ),
1192
+ new StyleRunProperties(
1193
+ new Italic(),
1194
+ new ItalicComplexScript()
1195
+ )
1196
+ )
1197
+ { Type = StyleValues.Paragraph, StyleId = "Quote" });
1198
+
1199
+ // Intense Quote (bold, larger indent)
1200
+ styles.Append(new Style(
1201
+ new StyleName { Val = "Intense Quote" },
1202
+ new BasedOn { Val = "Normal" },
1203
+ new NextParagraphStyle { Val = "Normal" },
1204
+ new PrimaryStyle(),
1205
+ new UIPriority { Val = 30 },
1206
+ new QuickStyle(),
1207
+ new StyleParagraphProperties(
1208
+ new Justification { Val = JustificationValues.Center },
1209
+ new Indentation { Left = "1440", Right = "1440" },
1210
+ new SpacingBetweenLines { After = "160" },
1211
+ new KeepNext(),
1212
+ new KeepLines(),
1213
+ new ParagraphBorders(
1214
+ new LeftBorder { Val = BorderValues.Single, Size = 24, Color = "4472C4", Space = 4 }
1215
+ )
1216
+ ),
1217
+ new StyleRunProperties(
1218
+ new Bold(),
1219
+ new Color { Val = "2F5496" }
1220
+ )
1221
+ )
1222
+ { Type = StyleValues.Paragraph, StyleId = "IntenseQuote" });
1223
+
1224
+ // --- LINKED CHARACTER STYLES ---
1225
+ // "Emphasis" linked character style (used for <Ctrl+E> in Word)
1226
+ styles.Append(new Style(
1227
+ new StyleName { Val = "Emphasis" },
1228
+ new PrimaryStyle(),
1229
+ new StyleRunProperties(
1230
+ new Italic()
1231
+ )
1232
+ )
1233
+ { Type = StyleValues.Character, StyleId = "Emphasis", Default = true });
1234
+
1235
+ // "Strong" linked character style
1236
+ styles.Append(new Style(
1237
+ new StyleName { Val = "Strong" },
1238
+ new PrimaryStyle(),
1239
+ new StyleRunProperties(
1240
+ new Bold()
1241
+ )
1242
+ )
1243
+ { Type = StyleValues.Character, StyleId = "Strong", Default = true });
1244
+
1245
+ // --- TOC STYLES (for Table of Contents) ---
1246
+ // TOC1-TOC9 are used by Word's TOC field for different heading levels
1247
+ styles.Append(new Style(
1248
+ new StyleName { Val = "TOC 1" },
1249
+ new BasedOn { Val = "Normal" },
1250
+ new Primary烙,
1251
+ new StyleParagraphProperties(
1252
+ new SpacingBetweenLines { After = "0" }
1253
+ )
1254
+ )
1255
+ { Type = StyleValues.Paragraph, StyleId = "TOC1" });
1256
+
1257
+ styles.Append(new Style(
1258
+ new StyleName { Val = "TOC 2" },
1259
+ new BasedOn { Val = "Normal" },
1260
+ new Primary烙,
1261
+ new StyleParagraphProperties(
1262
+ new Indentation { Left = "220" },
1263
+ new SpacingBetweenLines { After = "0" }
1264
+ )
1265
+ )
1266
+ { Type = StyleValues.Paragraph, StyleId = "TOC2" });
1267
+
1268
+ styles.Append(new Style(
1269
+ new StyleName { Val = "TOC 3" },
1270
+ new BasedOn { Val = "Normal" },
1271
+ new Primary烙,
1272
+ new StyleParagraphProperties(
1273
+ new Indentation { Left = "440" },
1274
+ new SpacingBetweenLines { After = "0" }
1275
+ )
1276
+ )
1277
+ { Type = StyleValues.Paragraph, StyleId = "TOC3" });
1278
+
1279
+ return styles;
1280
+ }
1281
+
1282
+ // --- ADDING STYLES TO A DOCUMENT ---
1283
+ public static void AddStylesToDocument(WordprocessingDocument doc, Styles styles)
1284
+ {
1285
+ var mainPart = doc.MainDocumentPart!;
1286
+
1287
+ // Get existing or create new styles part
1288
+ var stylesPart = mainPart.StyleDefinitionsPart;
1289
+ if (stylesPart == null)
1290
+ {
1291
+ stylesPart = mainPart.AddNewPart<StyleDefinitionsPart>();
1292
+ stylesPart.Styles = styles;
1293
+ }
1294
+ else
1295
+ {
1296
+ // Clear and replace existing styles
1297
+ stylesPart.Styles?.RemoveAllChildren();
1298
+ stylesPart.Styles = styles;
1299
+ }
1300
+ stylesPart.Styles.Save();
1301
+ }
1302
+ ```
1303
+
1304
+ ### 2.6 Importing Styles from Another Document
1305
+
1306
+ ```csharp
1307
+ // =============================================================================
1308
+ // IMPORTING STYLES FROM ANOTHER DOCUMENT
1309
+ // =============================================================================
1310
+ // Word's Organizer functionality allows copying styles between documents.
1311
+ // This is useful for templates, branding, or style normalization.
1312
+
1313
+ public static class StyleImporter
1314
+ {
1315
+ /// <summary>
1316
+ /// Imports styles from a source document into a target document.
1317
+ /// Can selectively import by type or name.
1318
+ /// </summary>
1319
+ public static void ImportStyles(
1320
+ WordprocessingDocument targetDoc,
1321
+ string sourcePath,
1322
+ bool overwriteExisting = false,
1323
+ Func<Style, bool>? filter = null)
1324
+ {
1325
+ // Open source as read-only
1326
+ using var sourceDoc = WordprocessingDocument.Open(sourcePath, isEditable: false);
1327
+ var sourceStylesPart = sourceDoc.MainDocumentPart?.StyleDefinitionsPart;
1328
+ if (sourceStylesPart?.Styles == null) return;
1329
+
1330
+ var targetStylesPart = targetDoc.MainDocumentPart!.StyleDefinitionsPart;
1331
+ if (targetStylesPart == null)
1332
+ {
1333
+ targetStylesPart = targetDoc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
1334
+ targetStylesPart.Styles = new Styles();
1335
+ }
1336
+
1337
+ var targetStyles = targetStylesPart.Styles!;
1338
+ var existingIds = targetStyles.Elements<Style>()
1339
+ .Select(s => s.StyleId?.Value ?? "")
1340
+ .ToHashSet();
1341
+
1342
+ foreach (var sourceStyle in sourceStylesPart.Styles.Elements<Style>())
1343
+ {
1344
+ // Apply filter if provided
1345
+ if (filter != null && !filter(sourceStyle))
1346
+ continue;
1347
+
1348
+ var styleId = sourceStyle.StyleId?.Value ?? "";
1349
+ if (string.IsNullOrEmpty(styleId)) continue;
1350
+
1351
+ // Skip if exists and not overwriting
1352
+ if (existingIds.Contains(styleId) && !overwriteExisting)
1353
+ continue;
1354
+
1355
+ // Clone the style (deep copy to avoid shared part issues)
1356
+ var clonedStyle = (Style)sourceStyle.CloneNode(true);
1357
+
1358
+ // If overwriting, remove existing first
1359
+ if (existingIds.Contains(styleId))
1360
+ {
1361
+ var existing = targetStyles.Elements<Style>()
1362
+ .FirstOrDefault(s => s.StyleId?.Value == styleId);
1363
+ existing?.Remove();
1364
+ }
1365
+
1366
+ targetStyles.Append(clonedStyle);
1367
+ existingIds.Add(styleId);
1368
+ }
1369
+
1370
+ targetStylesPart.Styles.Save();
1371
+ }
1372
+
1373
+ /// <summary>
1374
+ /// Imports only heading styles from source.
1375
+ /// </summary>
1376
+ public static void ImportHeadingStyles(WordprocessingDocument targetDoc, string sourcePath)
1377
+ {
1378
+ ImportStyles(
1379
+ targetDoc,
1380
+ sourcePath,
1381
+ overwriteExisting: true,
1382
+ filter: style => style.Name?.Val?.Value?.StartsWith("heading") == true ||
1383
+ style.Name?.Val?.Value?.StartsWith("Heading") == true);
1384
+ }
1385
+
1386
+ /// <summary>
1387
+ /// Imports all paragraph styles (not character, table, or numbering).
1388
+ /// </summary>
1389
+ public static void ImportParagraphStyles(WordprocessingDocument targetDoc, string sourcePath)
1390
+ {
1391
+ ImportStyles(
1392
+ targetDoc,
1393
+ sourcePath,
1394
+ overwriteExisting: false,
1395
+ filter: style => style.Type?.Value == StyleValues.Paragraph);
1396
+ }
1397
+ }
1398
+ ```
1399
+
1400
+ ---
1401
+
1402
+ ## 3. Character Formatting (RunProperties) — EXHAUSTIVE
1403
+
1404
+ ```csharp
1405
+ // =============================================================================
1406
+ // RUN PROPERTIES (CHARACTER FORMATTING) — COMPLETE REFERENCE
1407
+ // =============================================================================
1408
+ // RunProperties (w:rPr) controls inline text formatting. It can appear in:
1409
+ // 1. Style definitions (w:style/w:rPr) — applies to all text using that style
1410
+ // 2. Direct formatting in runs (w:r/w:rPr) — overrides style for specific text
1411
+ //
1412
+ // CHILD ELEMENT ORDER (w:rPr): MUST be in this order per OpenXML schema:
1413
+ // rStyle, rFonts, b, bCs, i, iCs, caps, smallCaps, strike, dstrike, vanish,
1414
+ // w:webHidden, color, sz, szCs, highlight, rendition/sz, u, vertAlign, shd,
1415
+ // baseTextStyle, eastAsianLayout, ligatures, bg, kern, spc, indent, snapToGrid,
1416
+ // glyphs, activeXfrm, legacy, specStyle, shadow, charsetConvert, iFormat,
1417
+ // w:templ
1418
+
1419
+ // --- MINIMAL RUN WITH FORMATTING ---
1420
+ // Any run can contain RunProperties to control appearance
1421
+ Paragraph minimalFormattedPara = new Paragraph(
1422
+ new Run(
1423
+ new RunProperties(
1424
+ new Bold(),
1425
+ new FontSize { Val = "28" } // 14pt (28 half-pts)
1426
+ ),
1427
+ new Text("Bold 14pt text")
1428
+ )
1429
+ );
1430
+
1431
+ // ===========================================================================
1432
+ // 3.1 RUNFONTS (Ascii, HighAnsi, EastAsia, ComplexScript)
1433
+ // ===========================================================================
1434
+ // RunFonts has 4 font "slots" for different scripts. Word uses fallback:
1435
+ // ASCII -> HighAnsi -> EastAsia -> ComplexScript
1436
+ // IMPORTANT: Always set at least Ascii and HighAnsi (they're often the same).
1437
+
1438
+ // Basic font specification
1439
+ RunProperties fonts1 = new RunProperties(
1440
+ new RunFonts
1441
+ {
1442
+ Ascii = "Calibri", // Western European characters (primary)
1443
+ HighAnsi = "Calibri", // Same as ASCII for Western docs
1444
+ EastAsia = "SimSun", // Simplified Chinese / East Asian
1445
+ ComplexScript = "Arial" // Arabic, Hebrew, Thai, Vietnamese
1446
+ }
1447
+ );
1448
+
1449
+ // Using theme fonts (references to theme definitions)
1450
+ RunProperties themeFonts = new RunProperties(
1451
+ new RunFonts
1452
+ {
1453
+ ASCIITheme = ThemeFontValues.Minor, // Minor font from theme (body)
1454
+ HighAnsiTheme = ThemeFontValues.Minor,
1455
+ EastAsiaTheme = ThemeFontValues.Major, // Major font from theme (headings)
1456
+ ComplexScriptTheme = ThemeFontValues.Minor,
1457
+ // When using theme, you can still override specific slots
1458
+ Ascii = "Calibri", HighAnsi = "Calibri" // Override minor with explicit font
1459
+ }
1460
+ );
1461
+
1462
+ // Complex script fonts (Arabic example)
1463
+ RunProperties arabicFonts = new RunProperties(
1464
+ new RunFonts
1465
+ {
1466
+ ComplexScript = "Traditional Arabic",
1467
+ // Word automatically handles Arabic shaping with complex script fonts
1468
+ }
1469
+ );
1470
+
1471
+ // East Asian with specific fallback
1472
+ RunProperties cjkFonts = new RunProperties(
1473
+ new RunFonts
1474
+ {
1475
+ Ascii = "Microsoft YaHei", // Western: Microsoft YaHei for Chinese
1476
+ HighAnsi = "Microsoft YaHei",
1477
+ EastAsia = "Microsoft YaHei", // East Asian: same font handles both
1478
+ ComplexScript = "Microsoft YaHei"
1479
+ }
1480
+ );
1481
+
1482
+ // Font substitution hints (rarely needed, for special cases)
1483
+ RunProperties hintFonts = new RunProperties(
1484
+ new RunFonts
1485
+ {
1486
+ Ascii = "Times New Roman",
1487
+ HighAnsi = "Times New Roman",
1488
+ Hint = FontStringsValues.EastAsia // Hint to Word: treat as East Asian font
1489
+ }
1490
+ );
1491
+
1492
+ // ===========================================================================
1493
+ // 3.2 FONTSIZE (sz, szCs) — HALF-POINTS!
1494
+ // ===========================================================================
1495
+ // CRITICAL: w:sz stores HALF-POINTS. 24 = 12pt, 48 = 24pt.
1496
+ // szCs = complex script size (for Arabic, Hebrew, etc.)
1497
+
1498
+ // Common font sizes
1499
+ RunProperties fontSize12pt = new RunProperties(
1500
+ new FontSize { Val = "24" }, // 12pt = 24 half-pts
1501
+ new FontSizeComplexScript { Val = "24" }
1502
+ );
1503
+
1504
+ RunProperties fontSize14pt = new RunProperties(
1505
+ new FontSize { Val = "28" }, // 14pt
1506
+ new FontSizeComplexScript { Val = "28" }
1507
+ );
1508
+
1509
+ RunProperties fontSize18pt = new RunProperties(
1510
+ new FontSize { Val = "36" }, // 18pt
1511
+ new FontSizeComplexScript { Val = "36" }
1512
+ );
1513
+
1514
+ RunProperties fontSize24pt = new RunProperties(
1515
+ new FontSize { Val = "48" }, // 24pt
1516
+ new FontSizeComplexScript { Val = "48" }
1517
+ );
1518
+
1519
+ // FontSize from double (helper)
1520
+ double targetPt = 11.0;
1521
+ int halfPts = (int)(targetPt * 2); // 22 for 11pt
1522
+ RunProperties dynamicFontSize = new RunProperties(
1523
+ new FontSize { Val = halfPts.ToString() },
1524
+ new FontSizeComplexScript { Val = halfPts.ToString() }
1525
+ );
1526
+
1527
+ // Legacy font size (some documents use csSize instead)
1528
+ // csSize = complex script size only
1529
+
1530
+ // ===========================================================================
1531
+ // 3.3 BOLD (b, bCs, b, bCs)
1532
+ // ===========================================================================
1533
+ // b = bold for ASCII/Latin
1534
+ // bCs = bold for complex script
1535
+ // Both should usually be set together
1536
+
1537
+ RunProperties bold = new RunProperties(
1538
+ new Bold(),
1539
+ new BoldComplexScript() // Always include both for consistent rendering
1540
+ );
1541
+
1542
+ // Bold with state control (on/off)
1543
+ RunProperties unbold = new RunProperties(
1544
+ new Bold { Val = OnOffValueValues.Off } // Explicitly turn off bold
1545
+ );
1546
+
1547
+ // Conditional bold (for complex scripts)
1548
+ // b={} with val=Off actually means "not bold" even if parent style says bold
1549
+ // This is how you "unbold" in a bold context
1550
+
1551
+ // ===========================================================================
1552
+ // 3.4 ITALIC (i, iCs)
1553
+ // ===========================================================================
1554
+ RunProperties italic = new RunProperties(
1555
+ new Italic(),
1556
+ new ItalicComplexScript()
1557
+ );
1558
+
1559
+ RunProperties unitalic = new RunProperties(
1560
+ new Italic { Val = OnOffValueValues.Off }
1561
+ );
1562
+
1563
+ // Word's "Italic" is the style. ComplexScript italic handles Arabic calligraphy etc.
1564
+
1565
+ // ===========================================================================
1566
+ // 3.5 UNDERLINE (u)
1567
+ // ===========================================================================
1568
+ // UnderlineValues enum has MANY options:
1569
+ // Single, Double, Thick, Wave, Dash, Dotted, DashDot, DashDotDot,
1570
+ // SingleAccounting, DoubleAccounting, TriWave, Nasized, DotDash, DotDotDash,
1571
+ // LongDash, ThickDash, LongDashDot, ThickLongDash, ThickDashDot, ThickDashDotDot
1572
+
1573
+ // Single underline (most common)
1574
+ RunProperties underlineSingle = new RunProperties(
1575
+ new Underline { Val = UnderlineValues.Single }
1576
+ );
1577
+
1578
+ // Double underline (often for edits/changes)
1579
+ RunProperties underlineDouble = new RunProperties(
1580
+ new Underline { Val = UnderlineValues.Double }
1581
+ );
1582
+
1583
+ // Thick single underline
1584
+ RunProperties underlineThick = new RunProperties(
1585
+ new Underline { Val = UnderlineValues.Thick }
1586
+ );
1587
+
1588
+ // Wave underline (often used for spelling errors in red)
1589
+ RunProperties underlineWave = new RunProperties(
1590
+ new Underline { Val = UnderlineValues.Wave }
1591
+ );
1592
+
1593
+ // Dotted underline
1594
+ RunProperties underlineDotted = new RunProperties(
1595
+ new Underline { Val = UnderlineValues.Dotted }
1596
+ );
1597
+
1598
+ // Dashed underline
1599
+ RunProperties underlineDashed = new RunProperties(
1600
+ new Underline { Val = UnderlineValues.Dash }
1601
+ );
1602
+
1603
+ // Dash-dot underline
1604
+ RunProperties underlineDashDot = new RunProperties(
1605
+ new Underline { Val = UnderlineValues.DotDash }
1606
+ );
1607
+
1608
+ // Accounting double underline (extends to both sides like accounting)
1609
+ RunProperties underlineAccounting = new RunProperties(
1610
+ new Underline { Val = UnderlineValues.DoubleAccounting }
1611
+ );
1612
+
1613
+ // With color specification
1614
+ RunProperties underlineColored = new RunProperties(
1615
+ new Underline { Val = UnderlineValues.Single, Color = "FF0000" } // Red underline
1616
+ );
1617
+
1618
+ // Without color (color="auto" = black)
1619
+ // With specific color using hex
1620
+ RunProperties underlineBlue = new RunProperties(
1621
+ new Underline { Val = UnderlineValues.Single, Color = "0000FF" }
1622
+ );
1623
+
1624
+ // Theme color on underline
1625
+ RunProperties underlineThemeColor = new RunProperties(
1626
+ new Underline
1627
+ {
1628
+ Val = UnderlineValues.Single,
1629
+ Color = "auto", // or omit for auto/black
1630
+ ThemeColor = ThemeColorValues.Accent1,
1631
+ ThemeTint = "99" // 60% opacity (hex 99 = 153/255 ≈ 60%)
1632
+ }
1633
+ );
1634
+
1635
+ // Turn off underline (in a underlined context)
1636
+ RunProperties noUnderline = new RunProperties(
1637
+ new Underline { Val = UnderlineValues.None }
1638
+ );
1639
+
1640
+ // ===========================================================================
1641
+ // 3.6 COLOR (color)
1642
+ // ===========================================================================
1643
+ // Color.Val is a 6-digit hex color (RRGGBB) WITHOUT the #
1644
+ // Word also supports 8-digit (AARRGGBB) for transparency
1645
+
1646
+ // Basic color
1647
+ RunProperties redText = new RunProperties(
1648
+ new Color { Val = "FF0000" } // Pure red
1649
+ );
1650
+
1651
+ RunProperties blueText = new RunProperties(
1652
+ new Color { Val = "0070C0" } // Office blue
1653
+ );
1654
+
1655
+ // Theme colors (references to document theme)
1656
+ RunProperties themeColorText = new RunProperties(
1657
+ new Color
1658
+ {
1659
+ Val = "FFFFFF", // Fallback
1660
+ ThemeColor = ThemeColorValues.Accent1,
1661
+ ThemeShade = "BF", // 75% darker (hex BF = 191/255 ≈ 75%)
1662
+ ThemeTint = "99" // 60% lighter (hex 99 = 153/255 ≈ 60%)
1663
+ }
1664
+ );
1665
+
1666
+ // Theme color shorthand
1667
+ RunProperties accent1Text = new RunProperties(
1668
+ new Color { Val = "4472C4" } // Direct hex is often simpler
1669
+ );
1670
+
1671
+ // With transparency (alpha channel, 8-digit hex)
1672
+ // AA=fully transparent, FF=fully opaque
1673
+ RunProperties transparentText = new RunProperties(
1674
+ new Color { Val = "80FF0000" } // 50% transparent red (AA=half, FF=red)
1675
+ );
1676
+
1677
+ // ===========================================================================
1678
+ // 3.7 HIGHLIGHT (highlight)
1679
+ // ===========================================================================
1680
+ // Highlight is a BACKGROUND color applied to the entire run.
1681
+ // Different from Shading (which is in run properties too).
1682
+ // Highlight enum values: DarkYellow, Yellow, Green, Cyan, Magenta, Blue,
1683
+ // DarkBlue, DarkCyan, DarkGreen, DarkMagenta, DarkRed, DarkYellow, LightGray,
1684
+ // LightGreen, LightOrange, LightPurple, LightRed, LightYellow, Navy, None,
1685
+ // Orange, Pink, Purple, Red, Teal, Turquoise, Yellow
1686
+
1687
+ // Yellow highlight (default for comments)
1688
+ RunProperties yellowHighlight = new RunProperties(
1689
+ new Highlight { Val = HighlightValues.Yellow }
1690
+ );
1691
+
1692
+ // Green highlight (for insertions)
1693
+ RunProperties greenHighlight = new RunProperties(
1694
+ new Highlight { Val = HighlightValues.Green }
1695
+ );
1696
+
1697
+ // Red highlight (for deletions)
1698
+ RunProperties redHighlight = new RunProperties(
1699
+ new Highlight { Val = HighlightValues.Red }
1700
+ );
1701
+
1702
+ // Blue highlight
1703
+ RunProperties blueHighlight = new RunProperties(
1704
+ new Highlight { Val = HighlightValues.Blue }
1705
+ );
1706
+
1707
+ // Cyan highlight (for feedback)
1708
+ RunProperties cyanHighlight = new RunProperties(
1709
+ new Highlight { Val = HighlightValues.Cyan }
1710
+ );
1711
+
1712
+ // Gray highlight (for search)
1713
+ RunProperties grayHighlight = new RunProperties(
1714
+ new Highlight { Val = HighlightValues.LightGray }
1715
+ );
1716
+
1717
+ // No highlight (turn off)
1718
+ RunProperties noHighlight = new RunProperties(
1719
+ new Highlight { Val = HighlightValues.None }
1720
+ );
1721
+
1722
+ // ===========================================================================
1723
+ // 3.8 STRIKETHROUGH (strike, dstrike)
1724
+ // ===========================================================================
1725
+ // strike = single strikethrough
1726
+ // dstrike = double strikethrough
1727
+
1728
+ // Single strikethrough (standard)
1729
+ RunProperties strikethrough = new RunProperties(
1730
+ new Strikethrough()
1731
+ );
1732
+
1733
+ // Double strikethrough (often for legal/editing)
1734
+ RunProperties doubleStrikethrough = new RunProperties(
1735
+ new DoubleStrike()
1736
+ );
1737
+
1738
+ // Turn off strikethrough
1739
+ RunProperties noStrikethrough = new RunProperties(
1740
+ new Strikethrough { Val = OnOffValueValues.Off }
1741
+ );
1742
+
1743
+ // ===========================================================================
1744
+ // 3.9 SUBSCRIPT/SUPERSCRIPT (verticalAlign)
1745
+ // ===========================================================================
1746
+ // VerticalTextAlignment enum: Baseline (normal), Subscript, Superscript
1747
+ // Subscript: lowers the text and reduces size
1748
+ // Superscript: raises the text and reduces size
1749
+
1750
+ // Superscript (e.g., 2 in X²)
1751
+ RunProperties superscript = new RunProperties(
1752
+ new VerticalTextAlignment { Val = VerticalPositionValues.Superscript }
1753
+ );
1754
+
1755
+ // Subscript (e.g., 2 in H₂O)
1756
+ RunProperties subscript = new RunProperties(
1757
+ new VerticalTextAlignment { Val = VerticalPositionValues.Subscript }
1758
+ );
1759
+
1760
+ // Baseline (normal) — explicit
1761
+ RunProperties baseline = new RunProperties(
1762
+ new VerticalTextAlignment { Val = VerticalPositionValues.Baseline }
1763
+ );
1764
+
1765
+ // ===========================================================================
1766
+ // 3.10 CAPS / ALLCAPS / SMALLCAPS (caps, smallCaps)
1767
+ // ===========================================================================
1768
+ // caps = ALL CAPS (converts lowercase to uppercase visually)
1769
+ // smallCaps = Small Caps (converts lowercase to uppercase but with smaller font)
1770
+
1771
+ // ALL CAPS (visual only, underlying text unchanged)
1772
+ RunProperties allCaps = new RunProperties(
1773
+ new Caps()
1774
+ );
1775
+
1776
+ // Small Caps (lowercase appears as smaller uppercase letters)
1777
+ RunProperties smallCaps = new RunProperties(
1778
+ new SmallCaps()
1779
+ );
1780
+
1781
+ // Both properties together (smallcaps takes precedence visually if both set)
1782
+ RunProperties emphasisCaps = new RunProperties(
1783
+ new SmallCaps(),
1784
+ new Caps()
1785
+ );
1786
+
1787
+ // Turn off caps
1788
+ RunProperties noCaps = new RunProperties(
1789
+ new Caps { Val = OnOffValueValues.Off }
1790
+ );
1791
+
1792
+ // ===========================================================================
1793
+ // 3.11 SPACING / KERNING (spacing)
1794
+ // ===========================================================================
1795
+ // Spacing.Val is in TWIPS (1/20 of a point, same as DXA)
1796
+ // Positive = add space, Negative = remove space
1797
+ // Range: -240 to +240 twips typically
1798
+
1799
+ // Add space between characters (letter spacing / kerning)
1800
+ RunProperties expandedSpacing = new RunProperties(
1801
+ new Spacing
1802
+ {
1803
+ Val = 100, // +100 twips = +5pt of space between characters
1804
+ // Space "100" = 5 points (100/20 = 5)
1805
+ }
1806
+ );
1807
+
1808
+ // Compress characters
1809
+ RunProperties compressedSpacing = new RunProperties(
1810
+ new Spacing
1811
+ {
1812
+ Val = -50, // -50 twips = -2.5pt (characters closer together)
1813
+ }
1814
+ );
1815
+
1816
+ // Normal spacing (remove any spacing adjustments)
1817
+ RunProperties normalSpacing = new RunProperties(
1818
+ new Spacing { Val = 0 }
1819
+ );
1820
+
1821
+ // Combined with other properties
1822
+ RunProperties spacedBold = new RunProperties(
1823
+ new Spacing { Val = 50 },
1824
+ new Bold()
1825
+ );
1826
+
1827
+ // ===========================================================================
1828
+ // 3.12 POSITION (position) — RAISED/LOWERED TEXT
1829
+ // ===========================================================================
1830
+ // Position.Val is in HALF-POINTS (not DXA!)
1831
+ // Positive = raise, Negative = lower
1832
+ // Range: -1584 to +1584 half-pts (-792pt to +792pt!)
1833
+
1834
+ // Raise text 6pt (12 half-points)
1835
+ RunProperties raised = new RunProperties(
1836
+ new Position
1837
+ {
1838
+ Val = 12 // +12 half-pts = +6pt raised
1839
+ }
1840
+ );
1841
+
1842
+ // Lower text 3pt
1843
+ RunProperties lowered = new RunProperties(
1844
+ new Position
1845
+ {
1846
+ Val = -6 // -6 half-pts = -3pt lowered
1847
+ }
1848
+ );
1849
+
1850
+ // Position is often used for:
1851
+ // - Footnote references
1852
+ // - Baseline alignment adjustments
1853
+ // - Mathematical subscripts/superscripts (though verticalAlign is better for these)
1854
+
1855
+ // ===========================================================================
1856
+ // 3.13 TEXT EFFECTS (textEffect)
1857
+ // ===========================================================================
1858
+ // TextEffectValues: shimmer, blinkBackground, etc.
1859
+ // These are decorative effects for special visual emphasis
1860
+
1861
+ // Shimmer effect (sparkle/light animation)
1862
+ RunProperties shimmerEffect = new RunProperties(
1863
+ new TextEffect
1864
+ {
1865
+ Val = TextEffectValues.Shimmer
1866
+ }
1867
+ );
1868
+
1869
+ // Blink background effect
1870
+ RunProperties blinkEffect = new RunProperties(
1871
+ new TextEffect
1872
+ {
1873
+ Val = TextEffectValues.BlinkBackground
1874
+ }
1875
+ );
1876
+
1877
+ // Anti-alias effect (smoother text rendering)
1878
+ // (usually applied via document settings, not per-run)
1879
+
1880
+ // ===========================================================================
1881
+ // 3.14 SHADING ON RUNS (shd)
1882
+ // ===========================================================================
1883
+ // Shading on a run applies a background color/pattern to the text background
1884
+ // Different from Highlight: Shading uses pattern fills, Highlight is solid colors
1885
+
1886
+ // Solid fill shading (run background color)
1887
+ RunProperties shadedRun = new RunProperties(
1888
+ new Shading
1889
+ {
1890
+ Val = ShadingPatternValues.Clear, // Clear = solid color
1891
+ Color = "auto", // auto = no border
1892
+ Fill = "FFFF00" // Yellow background
1893
+ }
1894
+ );
1895
+
1896
+ // Horizontal line pattern shading
1897
+ RunProperties hLineShading = new RunProperties(
1898
+ new Shading
1899
+ {
1900
+ Val = ShadingPatternValues.HorizontalLine, // Horizontal line pattern
1901
+ Color = "0000FF",
1902
+ Fill = "FFFF00"
1903
+ }
1904
+ );
1905
+
1906
+ // Reverse pattern (for special effects)
1907
+ RunProperties reverseShading = new RunProperties(
1908
+ new Shading
1909
+ {
1910
+ Val = ShadingPatternValues.ReverseDiagonalStripe,
1911
+ Color = "auto",
1912
+ Fill = "E0E0E0"
1913
+ }
1914
+ );
1915
+
1916
+ // Clear shading (remove)
1917
+ RunProperties noShading = new RunProperties(
1918
+ new Shading
1919
+ {
1920
+ Val = ShadingPatternValues.Clear,
1921
+ Fill = "auto"
1922
+ }
1923
+ );
1924
+
1925
+ // Thatch pattern (diagonal lines, like legal document)
1926
+ RunProperties thatchShading = new RunProperties(
1927
+ new Shading
1928
+ {
1929
+ Val = ShadingPatternValues.Thatch,
1930
+ Color = "000000",
1931
+ Fill = "FFFFFF"
1932
+ }
1933
+ );
1934
+
1935
+ // Common shading patterns:
1936
+ // Clear, Solid, HorizStripe, VertStripe, RevDiagStripe, DiagCross, DiagStripe,
1937
+ // ReverseDiagStripe, DiagHorizCross, ThinHorzStripe, ThinVertStripe,
1938
+ // ThinReverseDiagStripe, ThinDiagStripe, ThinDiagHorzCross, ThickHorzStripe,
1939
+ // ThickVertStripe, ThickDiagStripe, ThickDiagCross, ThickReverseDiagStripe,
1940
+ // ThickDiagonalCross, Shingle, ThickSmallCheck, SmallCheck, LargeCheck,
1941
+ // SmallConfetti, Confetti, Horizontal, Diagonal, BigConfetti, ZigZag
1942
+
1943
+ // ===========================================================================
1944
+ // 3.15 RUN STYLE (rStyle) — APPLY CHARACTER STYLE
1945
+ // ===========================================================================
1946
+ // RunStyle applies a character style to a run
1947
+ // The style must be defined in styles.xml first
1948
+
1949
+ // Apply character style by ID
1950
+ RunProperties styledRun = new RunProperties(
1951
+ new RunStyle { Val = "Emphasis" } // References a character style
1952
+ );
1953
+
1954
+ // Combined with direct formatting (direct overrides style)
1955
+ RunProperties styledWithOverride = new RunProperties(
1956
+ new RunStyle { Val = "Emphasis" },
1957
+ new Bold { Val = OnOffValueValues.Off } // Override: don't make it bold
1958
+ );
1959
+
1960
+ // ===========================================================================
1961
+ // 3.16 BORDER ON RUNS (rPr/bdr)
1962
+ // ===========================================================================
1963
+ // Run borders apply a border around individual characters (rarely used)
1964
+
1965
+ // WordArt-style character border
1966
+ RunProperties borderedRun = new RunProperties(
1967
+ new CharacterBorder(
1968
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "0000FF", Space = 1 },
1969
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "0000FF", Space = 1 },
1970
+ new LeftBorder { Val = BorderValues.Single, Size = 4, Color = "0000FF", Space = 1 },
1971
+ new RightBorder { Val = BorderValues.Single, Size = 4, Color = "0000FF", Space = 1 }
1972
+ )
1973
+ );
1974
+
1975
+ // Single border (typically used)
1976
+ RunProperties borderTop = new RunProperties(
1977
+ new CharacterBorder(
1978
+ new TopBorder { Val = BorderValues.Single, Size = 8, Color = "FF0000" }
1979
+ )
1980
+ );
1981
+
1982
+ // ===========================================================================
1983
+ // 3.17 VANISH / HIDDEN TEXT (vanish, webHidden)
1984
+ // ===========================================================================
1985
+ // vanish = hidden in both UI and print (like hidden field codes)
1986
+ // webHidden = hidden in web layout view
1987
+
1988
+ // Hidden text (doesn't appear in UI or print)
1989
+ RunProperties hiddenText = new RunProperties(
1990
+ new Vanish()
1991
+ );
1992
+
1993
+ // Hidden in web view only
1994
+ RunProperties webHiddenText = new RunProperties(
1995
+ new WebHidden()
1996
+ );
1997
+
1998
+ // Both combined
1999
+ RunProperties hiddenBothViews = new RunProperties(
2000
+ new Vanish(),
2001
+ new WebHidden()
2002
+ );
2003
+
2004
+ // Turn off hide (in a hidden context)
2005
+ RunProperties visible = new RunProperties(
2006
+ new Vanish { Val = OnOffValueValues.Off }
2007
+ );
2008
+
2009
+ // ===========================================================================
2010
+ // 3.18 RIGHT-TO-LEFT (bidi)
2011
+ // ===========================================================================
2012
+ // For bidirectional text (Arabic, Hebrew)
2013
+
2014
+ // Right-to-left text
2015
+ RunProperties rtlRun = new RunProperties(
2016
+ new RightToLeftText()
2017
+ );
2018
+
2019
+ // Normal direction
2020
+ RunProperties ltrRun = new RunProperties(
2021
+ new RightToLeftText { Val = OnOffValueValues.Off }
2022
+ );
2023
+
2024
+ // ===========================================================================
2025
+ // 3.19 LIGATURES (ligatures)
2026
+ // ===========================================================================
2027
+ // Ligatures combine adjacent characters for typography (fi, fl, ff, etc.)
2028
+ // Standard=0 means no ligatures, Standard=1 means common ligatures
2029
+
2030
+ // Standard ligatures (fi, fl, ff, ffi, ffl)
2031
+ RunProperties standardLigatures = new RunProperties(
2032
+ new Ligatures { Val = 1 } // Standard ligatures on
2033
+ );
2034
+
2035
+ // No ligatures
2036
+ RunProperties noLigatures = new RunProperties(
2037
+ new Ligatures { Val = 0 }
2038
+ );
2039
+
2040
+ // Historical ligatures (old-style, for fonts that support them)
2041
+ RunProperties historicalLigatures = new RunProperties(
2042
+ new Ligatures { Val = 2 } // Historical
2043
+ );
2044
+
2045
+ // ===========================================================================
2046
+ // 3.20 COMPLEX SCRIPT PROPERTIES (cs, csBdr, csShd, etc.)
2047
+ // ===========================================================================
2048
+ // Complex script properties mirror the ASCII properties but for
2049
+ // complex scripts (Arabic, Hebrew, Thai, etc.)
2050
+
2051
+ // Complex script bold
2052
+ RunProperties csBold = new RunProperties(
2053
+ new Bold(),
2054
+ new BoldComplexScript()
2055
+ );
2056
+
2057
+ // Complex script italic
2058
+ RunProperties csItalic = new RunProperties(
2059
+ new Italic(),
2060
+ new ItalicComplexScript()
2061
+ );
2062
+
2063
+ // Complex script underline
2064
+ RunProperties csUnderline = new RunProperties(
2065
+ new Underline { Val = UnderlineValues.Single },
2066
+ new UnderlineComplexScript { Val = UnderlineValues.Single }
2067
+ );
2068
+
2069
+ // Complex script border
2070
+ RunProperties csBorder = new RunProperties(
2071
+ new CharacterBorder(
2072
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "000080" }
2073
+ )
2074
+ );
2075
+
2076
+ // Complex script shading
2077
+ RunProperties csShading = new RunProperties(
2078
+ new Shading
2079
+ {
2080
+ Val = ShadingPatternValues.Clear,
2081
+ Color = "auto",
2082
+ Fill = "E6E6E6"
2083
+ }
2084
+ );
2085
+
2086
+ // ===========================================================================
2087
+ // 3.21 LANGUAGE (lang) — HYPHENATION/SPELL CHECK
2088
+ // ===========================================================================
2089
+ // Language determines hyphenation, spell-check dictionary, etc.
2090
+
2091
+ // English (US)
2092
+ RunProperties enUsText = new RunProperties(
2093
+ new Languages { Val = "en-US" }
2094
+ );
2095
+
2096
+ // English (UK)
2097
+ RunProperties enGbText = new RunProperties(
2098
+ new Languages { Val = "en-GB" }
2099
+ );
2100
+
2101
+ // French
2102
+ RunProperties frenchText = new RunProperties(
2103
+ new Languages { Val = "fr-FR" }
2104
+ );
2105
+
2106
+ // German
2107
+ RunProperties germanText = new RunProperties(
2108
+ new Languages { Val = "de-DE" }
2109
+ );
2110
+
2111
+ // Chinese (Simplified)
2112
+ RunProperties chineseText = new RunProperties(
2113
+ new Languages { Val = "zh-CN" }
2114
+ );
2115
+
2116
+ // Japanese
2117
+ RunProperties japaneseText = new RunProperties(
2118
+ new Languages { Val = "ja-JP" }
2119
+ );
2120
+
2121
+ // Arabic
2122
+ RunProperties arabicText = new RunProperties(
2123
+ new Languages { Val = "ar-SA" }
2124
+ );
2125
+
2126
+ // Hebrew
2127
+ RunProperties hebrewText = new RunProperties(
2128
+ new Languages { Val = "he-IL" }
2129
+ );
2130
+
2131
+ // No language (apply directly)
2132
+ RunProperties noLangText = new RunProperties(
2133
+ new Languages { Val = "" }
2134
+ );
2135
+
2136
+ // ===========================================================================
2137
+ // 3.22 KERNING (kern)
2138
+ // ===========================================================================
2139
+ // Kern adjusts character spacing based on character pairs
2140
+ // Value is in hundredths of a point (100 = 1pt)
2141
+
2142
+ // Enable kerning
2143
+ RunProperties kerning = new RunProperties(
2144
+ new Kern { Val = 20 } // 20 = 0.2pt minimum kerning threshold
2145
+ );
2146
+
2147
+ // Disable kerning
2148
+ RunProperties noKerning = new RunProperties(
2149
+ new Kern { Val = 0 }
2150
+ );
2151
+
2152
+ // Standard document kerning
2153
+ RunProperties standardKerning = new RunProperties(
2154
+ new Kern { Val = 12 } // 12 = 0.12pt
2155
+ );
2156
+
2157
+ // ===========================================================================
2158
+ // 3.23 SNAP TO GRID (snapToGrid)
2159
+ // ===========================================================================
2160
+ // SnapToGrid aligns characters to a document grid for consistent line spacing
2161
+
2162
+ // Enable snap to grid
2163
+ RunProperties snapToGrid = new RunProperties(
2164
+ new SnapToGrid()
2165
+ );
2166
+
2167
+ // Disable snap to grid
2168
+ RunProperties noSnapToGrid = new RunProperties(
2169
+ new SnapToGrid { Val = OnOffValueValues.Off }
2170
+ );
2171
+
2172
+ // ===========================================================================
2173
+ // 3.24 COMBINED RUN FORMATTING EXAMPLE
2174
+ // ===========================================================================
2175
+ // Complete run properties combining many options
2176
+
2177
+ RunProperties complexRunProps = new RunProperties(
2178
+ // Style reference (should be first per schema)
2179
+ new RunStyle { Val = "Emphasis" },
2180
+
2181
+ // Font
2182
+ new RunFonts
2183
+ {
2184
+ Ascii = "Georgia",
2185
+ HighAnsi = "Georgia",
2186
+ EastAsia = "SimSun"
2187
+ },
2188
+
2189
+ // Bold + Bold Complex Script
2190
+ new Bold(),
2191
+ new BoldComplexScript(),
2192
+
2193
+ // Italic + Italic Complex Script
2194
+ new Italic(),
2195
+ new ItalicComplexScript(),
2196
+
2197
+ // Underline
2198
+ new Underline { Val = UnderlineValues.Single, Color = "000080" },
2199
+
2200
+ // Font size (14pt)
2201
+ new FontSize { Val = "28" },
2202
+ new FontSizeComplexScript { Val = "28" },
2203
+
2204
+ // Color
2205
+ new Color { Val = "000080" }, // Navy blue
2206
+
2207
+ // Language
2208
+ new Languages { Val = "en-US" },
2209
+
2210
+ // Spacing (slightly expanded)
2211
+ new Spacing { Val = 50 },
2212
+
2213
+ // Small caps
2214
+ new SmallCaps(),
2215
+
2216
+ // Highlight
2217
+ new Highlight { Val = HighlightValues.LightGray },
2218
+
2219
+ // Shadow (decorative)
2220
+ new Shadow()
2221
+ );
2222
+
2223
+ // ===========================================================================
2224
+ // 3.25 APPLYING RUN PROPERTIES TO RUNS
2225
+ // ===========================================================================
2226
+ // RunProperties can be applied in multiple ways:
2227
+
2228
+ // Method 1: Inline in Run (direct formatting)
2229
+ Paragraph inlineFormatting = new Paragraph(
2230
+ new Run(
2231
+ new RunProperties(
2232
+ new Bold(),
2233
+ new Color { Val = "FF0000" }
2234
+ ),
2235
+ new Text("This is bold red text")
2236
+ )
2237
+ );
2238
+
2239
+ // Method 2: Via RunStyle (character style)
2240
+ Paragraph styleFormatting = new Paragraph(
2241
+ new Run(
2242
+ new RunStyle { Val = "MyCharStyle" },
2243
+ new Text("This uses the MyCharStyle character style")
2244
+ )
2245
+ );
2246
+
2247
+ // Method 3: Mix (direct overrides style)
2248
+ Paragraph mixedFormatting = new Paragraph(
2249
+ new Run(
2250
+ new RunProperties(
2251
+ new RunStyle { Val = "Emphasis" }, // Apply style first
2252
+ new Bold { Val = OnOffValueValues.Off } // Override: unbold
2253
+ ),
2254
+ new Text("Emphasis style but not bold")
2255
+ )
2256
+ );
2257
+
2258
+ // Method 4: Empty RunProperties to clear formatting
2259
+ Paragraph clearedFormatting = new Paragraph(
2260
+ new Run(
2261
+ new RunProperties(
2262
+ new Bold { Val = OnOffValueValues.Off },
2263
+ new Italic { Val = OnOffValueValues.Off },
2264
+ new Underline { Val = UnderlineValues.None },
2265
+ new Color { Val = "000000" },
2266
+ new FontSize { Val = "22" }
2267
+ ),
2268
+ new Text("Manually reset to defaults")
2269
+ )
2270
+ );
2271
+ ```
2272
+
2273
+ ---
2274
+
2275
+ ## 4. Paragraph Formatting (ParagraphProperties) — EXHAUSTIVE
2276
+
2277
+ ```csharp
2278
+ // =============================================================================
2279
+ // PARAGRAPH FORMATTING (PARAGRAPHPROPERTIES) — COMPLETE REFERENCE
2280
+ // =============================================================================
2281
+ // ParagraphProperties (w:pPr) controls paragraph-level formatting. It can appear in:
2282
+ // 1. Style definitions (w:style/w:pPr) — applies to all paragraphs using that style
2283
+ // 2. Direct formatting in paragraphs (w:p/w:pPr) — overrides style for specific paragraphs
2284
+ //
2285
+ // CHILD ELEMENT ORDER (w:pPr): MUST be in this order per OpenXML schema:
2286
+ // pStyle, keepNext, keepLines, pageBreakBefore, widowControl, numPr, pBdr,
2287
+ // shd, tabs, suppressAutoHyphens, spacing, ind, contextualSpacing,
2288
+ // mirrorIndents, oMath, textDirection, textAlignment, textboxTightWrap,
2289
+ // outlineLvl, divId, cnfStyle, rPr, sectPr, pPrChange
2290
+ //
2291
+ // CRITICAL: sectPr must be LAST child of w:body, but LAST BUT ONE in w:pPr context.
2292
+ // In body, sectPr defines section properties. In pPr, sectPr defines section break before paragraph.
2293
+
2294
+ // ===========================================================================
2295
+ // 4.1 JUSTIFICATION / ALIGNMENT (jc)
2296
+ // ===========================================================================
2297
+ // JustificationValues enum: Left, Center, Right, Both (Justify), Distribute,
2298
+ // ThaiDistribute, Justified (same as Both in most cases)
2299
+
2300
+ // Left justification (default for LTR languages)
2301
+ ParagraphProperties justifyLeft = new ParagraphProperties(
2302
+ new Justification { Val = JustificationValues.Left }
2303
+ );
2304
+
2305
+ // Center justification
2306
+ ParagraphProperties justifyCenter = new ParagraphProperties(
2307
+ new Justification { Val = JustificationValues.Center }
2308
+ );
2309
+
2310
+ // Right justification (common in Arabic/Hebrew documents)
2311
+ ParagraphProperties justifyRight = new ParagraphProperties(
2312
+ new Justification { Val = JustificationValues.Right }
2313
+ );
2314
+
2315
+ // Both/Justify (stretches lines to fill width — standard for books/newspapers)
2316
+ ParagraphProperties justifyBoth = new ParagraphProperties(
2317
+ new Justification { Val = JustificationValues.Both }
2318
+ );
2319
+
2320
+ // Distribute (each line individually stretched to fill — no ragging)
2321
+ // Often used in Asian typography
2322
+ ParagraphProperties justifyDistribute = new ParagraphProperties(
2323
+ new Justification { Val = JustificationValues.Distribute }
2324
+ );
2325
+
2326
+ // ThaiDistribute (special handling for Thai script)
2327
+ ParagraphProperties justifyThaiDistribute = new ParagraphProperties(
2328
+ new Justification { Val = JustificationValues.ThaiDistribute }
2329
+ );
2330
+
2331
+ // Center justification on a line (for titles)
2332
+ Paragraph titlePara = new Paragraph(
2333
+ new ParagraphProperties(
2334
+ new Justification { Val = JustificationValues.Center }
2335
+ ),
2336
+ new Run(new Text("Centered Title"))
2337
+ );
2338
+
2339
+ // ===========================================================================
2340
+ // 4.2 INDENTATION (ind)
2341
+ // ===========================================================================
2342
+ // All indentation values in DXA (1 inch = 1440 DXA, 1 cm ≈ 567 DXA)
2343
+ // Positive = indent rightward, Negative = indent leftward
2344
+ //
2345
+ // Left/Right: from page edge
2346
+ // FirstLine: extra indent for first line (positive = indent right, negative = outdent)
2347
+ // Hanging: amount to "hang" first line (negative moves first line left of body)
2348
+ // FirstLineChars: CJK-specific, specifies in character counts
2349
+
2350
+ // Basic left indent (1 inch from left edge)
2351
+ ParagraphProperties indentLeft1Inch = new ParagraphProperties(
2352
+ new Indentation { Left = "1440" } // 1440 DXA = 1 inch
2353
+ );
2354
+
2355
+ // Left indent with hanging first line (negative FirstLine)
2356
+ ParagraphProperties hangingIndent = new ParagraphProperties(
2357
+ new Indentation
2358
+ {
2359
+ Left = "720", // Body starts 0.5 inch from left
2360
+ FirstLine = "-720" // First line aligns with body start
2361
+ }
2362
+ );
2363
+
2364
+ // FirstLine positive (first line indented more than body)
2365
+ ParagraphProperties firstLineIndent = new ParagraphProperties(
2366
+ new Indentation
2367
+ {
2368
+ Left = "1440", // Body at 1 inch
2369
+ FirstLine = "720" // First line at 1.5 inch (additional 0.5 inch)
2370
+ }
2371
+ );
2372
+
2373
+ // Right indent
2374
+ ParagraphProperties indentRight = new ParagraphProperties(
2375
+ new Indentation { Right = "1440" } // 1 inch from right edge
2376
+ );
2377
+
2378
+ // Both left and right indent (centered block)
2379
+ ParagraphProperties blockIndent = new ParagraphProperties(
2380
+ new Indentation
2381
+ {
2382
+ Left = "1440", // 1 inch from left
2383
+ Right = "1440" // 1 inch from right
2384
+ }
2385
+ );
2386
+
2387
+ // Hanging indent (classic for bibliographies, numbered lists)
2388
+ // First line hangs to the left of the body
2389
+ ParagraphProperties hangingIndent720 = new ParagraphProperties(
2390
+ new Indentation
2391
+ {
2392
+ Left = "1440", // Body indent = 1 inch
2393
+ Hanging = "720" // First line hangs 0.5 inch to the left of body
2394
+ }
2395
+ );
2396
+
2397
+ // Outdent (first line starts BEFORE body start)
2398
+ ParagraphProperties outdent = new ParagraphProperties(
2399
+ new Indentation
2400
+ {
2401
+ Left = "720", // Body at 0.5 inch
2402
+ FirstLine = "-720" // First line at 0 (page edge)
2403
+ }
2404
+ );
2405
+
2406
+ // Line-specific: negative left indent (pull into margin)
2407
+ ParagraphProperties negativeIndent = new ParagraphProperties(
2408
+ new Indentation { Left = "-720" } // 0.5 inch into left margin
2409
+ );
2410
+
2411
+ // CJK FirstLineChars (character-based first line indent)
2412
+ // This converts character count to DXA based on font metrics
2413
+ ParagraphProperties cjkFirstLine = new ParagraphProperties(
2414
+ new Indentation
2415
+ {
2416
+ Left = "567", // Body at 1 cm
2417
+ FirstLineChars = 200 // 2 characters extra indent (200 = 2 chars × 100)
2418
+ }
2419
+ );
2420
+
2421
+ // CJK HangingChars
2422
+ ParagraphProperties cjkHanging = new ParagraphProperties(
2423
+ new Indentation
2424
+ {
2425
+ Left = "567",
2426
+ HangingChars = 100 // 1 character hanging
2427
+ }
2428
+ );
2429
+
2430
+ // ===========================================================================
2431
+ // 4.3 SPACING BETWEEN LINES (spacing)
2432
+ // ===========================================================================
2433
+ // SpacingBetweenLines has multiple attributes:
2434
+ // Before: space above paragraph in DXA
2435
+ // After: space below paragraph in DXA
2436
+ // Line: line height (in DXA for Exact/AtLeast, or value×240 for Auto)
2437
+ // LineRule: Auto (multiple of single), Exact (fixed DXA), AtLeast (minimum DXA)
2438
+ //
2439
+ // Special Line values for Auto:
2440
+ // 240 = single spacing
2441
+ // 360 = 1.5 line spacing
2442
+ // 480 = double spacing
2443
+ // 120 = half spacing (rare)
2444
+ // For other multiples: Line = (desired spacing in points) × 20
2445
+
2446
+ // Space before only
2447
+ ParagraphProperties spaceBefore = new ParagraphProperties(
2448
+ new SpacingBetweenLines { Before = "240" } // 240 DXA = 12pt before
2449
+ );
2450
+
2451
+ // Space after only
2452
+ ParagraphProperties spaceAfter = new ParagraphProperties(
2453
+ new SpacingBetweenLines { After = "200" } // 200 DXA = 10pt after
2454
+ );
2455
+
2456
+ // Both before and after
2457
+ ParagraphProperties spaceBoth = new ParagraphProperties(
2458
+ new SpacingBetweenLines
2459
+ {
2460
+ Before = "120",
2461
+ After = "120"
2462
+ }
2463
+ );
2464
+
2465
+ // SINGLE LINE SPACING (Auto rule)
2466
+ ParagraphProperties singleSpacing = new ParagraphProperties(
2467
+ new SpacingBetweenLines
2468
+ {
2469
+ Line = "240",
2470
+ LineRule = LineSpacingRuleValues.Auto // 240 = 1.0× line height
2471
+ }
2472
+ );
2473
+
2474
+ // DOUBLE LINE SPACING
2475
+ ParagraphProperties doubleSpacing = new ParagraphProperties(
2476
+ new SpacingBetweenLines
2477
+ {
2478
+ Line = "480",
2479
+ LineRule = LineSpacingRuleValues.Auto // 480 = 2.0× line height
2480
+ }
2481
+ );
2482
+
2483
+ // 1.5 LINE SPACING
2484
+ ParagraphProperties oneAndHalfSpacing = new ParagraphProperties(
2485
+ new SpacingBetweenLines
2486
+ {
2487
+ Line = "360",
2488
+ LineRule = LineSpacingRuleValues.Auto // 360 = 1.5× line height
2489
+ }
2490
+ );
2491
+
2492
+ // EXACT LINE HEIGHT (fixed height, regardless of content)
2493
+ ParagraphProperties exactLineHeight = new ParagraphProperties(
2494
+ new SpacingBetweenLines
2495
+ {
2496
+ Line = "360", // 360 DXA = 18pt
2497
+ LineRule = LineSpacingRuleValues.Exact // Exactly 18pt, even if text overflows
2498
+ }
2499
+ );
2500
+
2501
+ // AT-LEAST LINE HEIGHT (minimum, grows if needed)
2502
+ ParagraphProperties atLeastLineHeight = new ParagraphProperties(
2503
+ new SpacingBetweenLines
2504
+ {
2505
+ Line = "288", // At least 14.4pt
2506
+ LineRule = LineSpacingRuleValues.AtLeast // At least 14.4pt, more if content requires
2507
+ }
2508
+ );
2509
+
2510
+ // LINE SPACING WITH SPACE BEFORE/AFTER
2511
+ ParagraphProperties paragraphWithSpacing = new ParagraphProperties(
2512
+ new SpacingBetweenLines
2513
+ {
2514
+ Before = "480", // 24pt before (for heading paragraphs)
2515
+ After = "240", // 12pt after
2516
+ Line = "276", // 1.15× line spacing
2517
+ LineRule = LineSpacingRuleValues.Auto
2518
+ }
2519
+ );
2520
+
2521
+ // SPACE BETWEEN LINES EXPLAINED:
2522
+ // LineRule = Auto:
2523
+ // - Line value is a multiple of 240 (single spacing = 240)
2524
+ // - Word multiplies by the font size to get actual line height
2525
+ // - Example: Line="360" with 11pt font = 11pt × 1.5 = 16.5pt actual
2526
+ // - Most common setting for body text
2527
+ //
2528
+ // LineRule = Exact:
2529
+ // - Line value is in DXA directly
2530
+ // - Line="360" = exactly 18pt, period
2531
+ // - Text that exceeds will overflow
2532
+ // - Used for fixed-height rows in tables
2533
+ //
2534
+ // LineRule = AtLeast:
2535
+ // - Line value is minimum in DXA
2536
+ // - Line="288" = at least 14.4pt, grows if text is taller
2537
+ // - Used when you need minimum spacing but content varies
2538
+
2539
+ // ===========================================================================
2540
+ // 4.4 KEEP OPTIONS (keepNext, keepLines, widowControl)
2541
+ // ===========================================================================
2542
+ // These control how paragraphs interact with page breaks
2543
+
2544
+ // KEEP NEXT: Keep this paragraph on same page as the following paragraph
2545
+ // Essential for headings (don't separate heading from first paragraph)
2546
+ ParagraphProperties keepWithNext = new ParagraphProperties(
2547
+ new KeepNext()
2548
+ );
2549
+
2550
+ // KEEP LINES: Keep all lines of this paragraph together (no page break inside)
2551
+ // Used for: table rows, list items, or paragraphs that shouldn't split
2552
+ ParagraphProperties keepLinesTogether = new ParagraphProperties(
2553
+ new KeepLines()
2554
+ );
2555
+
2556
+ // BOTH: Keep next AND keep lines together
2557
+ ParagraphProperties keepBoth = new ParagraphProperties(
2558
+ new KeepNext(),
2559
+ new KeepLines()
2560
+ );
2561
+
2562
+ // WIDOW CONTROL: Prevent single lines at page top/bottom (widow/orphan control)
2563
+ // Default is ON in Word. Only disable if you want orphans/widows.
2564
+ ParagraphProperties widowControl = new ParagraphProperties(
2565
+ new WidowControl()
2566
+ );
2567
+
2568
+ // NO WIDOW CONTROL (allow single lines at page breaks)
2569
+ ParagraphProperties noWidowControl = new ParagraphProperties(
2570
+ new WidowControl { Val = OnOffValueValues.Off }
2571
+ );
2572
+
2573
+ // PAGE BREAK BEFORE: Start this paragraph on a new page
2574
+ ParagraphProperties pageBreakBefore = new ParagraphProperties(
2575
+ new PageBreakBefore()
2576
+ );
2577
+
2578
+ // Combined: Heading style (keep with next, keep lines, page break before)
2579
+ ParagraphProperties headingProps = new ParagraphProperties(
2580
+ new KeepNext(),
2581
+ new KeepLines(),
2582
+ new PageBreakBefore(),
2583
+ new WidowControl(),
2584
+ new SpacingBetweenLines { Before = "480", After = "120" }
2585
+ );
2586
+
2587
+ // ===========================================================================
2588
+ // 4.5 OUTLINE LEVEL (outlineLvl)
2589
+ // ===========================================================================
2590
+ // OutlineLevel defines the heading level for document structure (TOC, Navigation)
2591
+ // Values 0-8 correspond to Heading 1 through Heading 9
2592
+ // Word uses this to identify headings in the Navigation Pane
2593
+
2594
+ // Level 0 = Heading 1
2595
+ ParagraphProperties outlineLevel1 = new ParagraphProperties(
2596
+ new OutlineLevel { Val = 0 }
2597
+ );
2598
+
2599
+ // Level 1 = Heading 2
2600
+ ParagraphProperties outlineLevel2 = new ParagraphProperties(
2601
+ new OutlineLevel { Val = 1 }
2602
+ );
2603
+
2604
+ // Level 5 = Heading 6
2605
+ ParagraphProperties outlineLevel6 = new ParagraphProperties(
2606
+ new OutlineLevel { Val = 5 }
2607
+ );
2608
+
2609
+ // Level 8 = last possible level
2610
+ ParagraphProperties outlineLevel8 = new ParagraphProperties(
2611
+ new OutlineLevel { Val = 8 }
2612
+ );
2613
+
2614
+ // TOC integration: When you insert a TOC field, Word looks for paragraphs
2615
+ // with outlineLevel to generate entries. Without outlineLevel, TOC won't
2616
+ // recognize the heading.
2617
+
2618
+ // Heading 1 style example (combining with style reference)
2619
+ Paragraph heading1 = new Paragraph(
2620
+ new ParagraphProperties(
2621
+ new ParagraphStyleId { Val = "Heading1" }, // Style reference
2622
+ new OutlineLevel { Val = 0 } // Also set outline level directly
2623
+ ),
2624
+ new Run(new Text("Chapter One"))
2625
+ );
2626
+
2627
+ // ===========================================================================
2628
+ // 4.6 PARAGRAPH BORDERS (pBdr)
2629
+ // ===========================================================================
2630
+ // Paragraph borders draw lines around/adjacent to paragraphs
2631
+ // Four borders: Top, Left, Bottom, Right, Between, Bar
2632
+
2633
+ // Simple bottom border
2634
+ ParagraphProperties bottomBorder = new ParagraphProperties(
2635
+ new ParagraphBorders(
2636
+ new BottomBorder
2637
+ {
2638
+ Val = BorderValues.Single,
2639
+ Size = 4,
2640
+ Color = "000000",
2641
+ Space = 4 // Space between text and border in DXA
2642
+ }
2643
+ )
2644
+ );
2645
+
2646
+ // Top border only
2647
+ ParagraphProperties topBorder = new ParagraphProperties(
2648
+ new ParagraphBorders(
2649
+ new TopBorder
2650
+ {
2651
+ Val = BorderValues.Single,
2652
+ Size = 8,
2653
+ Color = "4472C4",
2654
+ Space = 4
2655
+ }
2656
+ )
2657
+ );
2658
+
2659
+ // Double line bottom border (common for headings)
2660
+ ParagraphProperties doubleBottomBorder = new ParagraphProperties(
2661
+ new ParagraphBorders(
2662
+ new BottomBorder
2663
+ {
2664
+ Val = BorderValues.Double,
2665
+ Size = 4,
2666
+ Color = "000000",
2667
+ Space = 4
2668
+ }
2669
+ )
2670
+ );
2671
+
2672
+ // All four borders
2673
+ ParagraphProperties allBorders = new ParagraphProperties(
2674
+ new ParagraphBorders(
2675
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "CCCCCC", Space = 1 },
2676
+ new LeftBorder { Val = BorderValues.Single, Size = 4, Color = "CCCCCC", Space = 4 },
2677
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "CCCCCC", Space = 1 },
2678
+ new RightBorder { Val = BorderValues.Single, Size = 4, Color = "CCCCCC", Space = 4 }
2679
+ )
2680
+ );
2681
+
2682
+ // Between border (line between adjacent paragraphs)
2683
+ // Used for paragraph groups with separator lines
2684
+ ParagraphProperties withBetweenBorder = new ParagraphProperties(
2685
+ new ParagraphBorders(
2686
+ new BetweenBorder
2687
+ {
2688
+ Val = BorderValues.Single,
2689
+ Size = 2,
2690
+ Color = "CCCCCC",
2691
+ Space = 4
2692
+ }
2693
+ )
2694
+ );
2695
+
2696
+ // Bar border (vertical bar on one side)
2697
+ // Val can be Left or Right — a solid bar in the margin
2698
+ ParagraphProperties leftBarBorder = new ParagraphProperties(
2699
+ new ParagraphBorders(
2700
+ new BarBorder { Val = BorderValues.Left, Color = "000080", Size = 12 }
2701
+ )
2702
+ );
2703
+
2704
+ // Thick top border with color
2705
+ ParagraphProperties thickTopBorder = new ParagraphProperties(
2706
+ new ParagraphBorders(
2707
+ new TopBorder
2708
+ {
2709
+ Val = BorderValues.Thick,
2710
+ Size = 12,
2711
+ Color = "2F5496",
2712
+ Space = 8
2713
+ }
2714
+ )
2715
+ );
2716
+
2717
+ // Wave border (decorative)
2718
+ ParagraphProperties waveBorder = new ParagraphProperties(
2719
+ new ParagraphBorders(
2720
+ new BottomBorder
2721
+ {
2722
+ Val = BorderValues.Wave,
2723
+ Size = 6,
2724
+ Color = "FF0000",
2725
+ Space = 4
2726
+ }
2727
+ )
2728
+ );
2729
+
2730
+ // Border.NONE to explicitly remove borders
2731
+ ParagraphProperties noBorders = new ParagraphProperties(
2732
+ new ParagraphBorders(
2733
+ new BottomBorder { Val = BorderValues.None }
2734
+ )
2735
+ );
2736
+
2737
+ // ===========================================================================
2738
+ // 4.7 SHADING / BACKGROUND (shd)
2739
+ // ===========================================================================
2740
+ // Shading applies background color/pattern to the paragraph area
2741
+ // Different from run-level highlight (which only covers the text)
2742
+
2743
+ // Solid color shading (paragraph background)
2744
+ ParagraphProperties shadedBackground = new ParagraphProperties(
2745
+ new Shading
2746
+ {
2747
+ Val = ShadingPatternValues.Clear,
2748
+ Color = "auto",
2749
+ Fill = "E6F2FF" // Light blue
2750
+ }
2751
+ );
2752
+
2753
+ // Gray shading (common for quotes, notes)
2754
+ ParagraphProperties grayBackground = new ParagraphProperties(
2755
+ new Shading
2756
+ {
2757
+ Val = ShadingPatternValues.Clear,
2758
+ Color = "auto",
2759
+ Fill = "F2F2F2" // Light gray
2760
+ }
2761
+ );
2762
+
2763
+ // Accent1 theme color shading
2764
+ ParagraphProperties themedBackground = new ParagraphProperties(
2765
+ new Shading
2766
+ {
2767
+ Val = ShadingPatternValues.Clear,
2768
+ Color = "auto",
2769
+ Fill = "D9E2F3", // Light blue accent
2770
+ ThemeColor = ThemeColorValues.Accent1,
2771
+ ThemeShade = "80" // 50% shade
2772
+ }
2773
+ );
2774
+
2775
+ // Pattern shading (horizontal lines)
2776
+ ParagraphProperties stripedBackground = new ParagraphProperties(
2777
+ new Shading
2778
+ {
2779
+ Val = ShadingPatternValues.HorizStripe,
2780
+ Color = "000000",
2781
+ Fill = "FFFFFF"
2782
+ }
2783
+ );
2784
+
2785
+ // Diagonal stripe shading
2786
+ ParagraphProperties diagonalBackground = new ParagraphProperties(
2787
+ new Shading
2788
+ {
2789
+ Val = ShadingPatternValues.ReverseDiagStripe,
2790
+ Color = "auto",
2791
+ Fill = "FFF2CC" // Light yellow
2792
+ }
2793
+ );
2794
+
2795
+ // Clear shading (remove background)
2796
+ ParagraphProperties noBackground = new ParagraphProperties(
2797
+ new Shading
2798
+ {
2799
+ Val = ShadingPatternValues.Clear,
2800
+ Fill = "auto"
2801
+ }
2802
+ );
2803
+
2804
+ // Combined shading and border (common for callout boxes)
2805
+ ParagraphProperties calloutBox = new ParagraphProperties(
2806
+ new ParagraphBorders(
2807
+ new LeftBorder
2808
+ {
2809
+ Val = BorderValues.Single,
2810
+ Size = 24,
2811
+ Color = "4472C4",
2812
+ Space = 8
2813
+ }
2814
+ ),
2815
+ new Shading
2816
+ {
2817
+ Val = ShadingPatternValues.Clear,
2818
+ Color = "auto",
2819
+ Fill = "D9E2F3"
2820
+ },
2821
+ new Indentation { Left = "720" }
2822
+ );
2823
+
2824
+ // ===========================================================================
2825
+ // 4.8 TABS (tabs)
2826
+ // ===========================================================================
2827
+ // TabStops define where tab characters position text
2828
+ // Each tab has: position (DXA from left margin), alignment, leader
2829
+
2830
+ // Single left tab at 1 inch
2831
+ ParagraphProperties leftTab = new ParagraphProperties(
2832
+ new Tabs(
2833
+ new TabStop { Position = 1440, Val = TabStopValues.Left }
2834
+ )
2835
+ );
2836
+
2837
+ // Multiple tabs
2838
+ ParagraphProperties multipleTabs = new ParagraphProperties(
2839
+ new Tabs(
2840
+ new TabStop { Position = 1440, Val = TabStopValues.Left }, // 1"
2841
+ new TabStop { Position = 2880, Val = TabStopValues.Center }, // 2"
2842
+ new TabStop { Position = 4320, Val = TabStopValues.Right }, // 3"
2843
+ new TabStop { Position = 5760, Val = TabStopValues.Decimal, TabChar = '.' } // 4" decimal
2844
+ )
2845
+ );
2846
+
2847
+ // Tab with dot leader (dots connecting to tab position)
2848
+ ParagraphProperties dotLeaderTab = new ParagraphProperties(
2849
+ new Tabs(
2850
+ new TabStop
2851
+ {
2852
+ Position = 4320, // 3 inches
2853
+ Val = TabStopValues.Left,
2854
+ Leader = TabStopLeaderCharValues.Dot
2855
+ }
2856
+ )
2857
+ );
2858
+
2859
+ // Tab with dash leader
2860
+ ParagraphProperties dashLeaderTab = new ParagraphProperties(
2861
+ new Tabs(
2862
+ new TabStop
2863
+ {
2864
+ Position = 4320,
2865
+ Val = TabStopValues.Left,
2866
+ Leader = TabStopLeaderCharValues.Dash
2867
+ }
2868
+ )
2869
+ );
2870
+
2871
+ // Tab with underscore leader
2872
+ ParagraphProperties underscoreLeaderTab = new ParagraphProperties(
2873
+ new Tabs(
2874
+ new TabStop
2875
+ {
2876
+ Position = 4320,
2877
+ Val = TabStopValues.Left,
2878
+ Leader = TabStopLeaderCharValues.Underscore
2879
+ }
2880
+ )
2881
+ );
2882
+
2883
+ // Tab with heavy line leader
2884
+ ParagraphProperties heavyLeaderTab = new ParagraphProperties(
2885
+ new TabStop
2886
+ {
2887
+ Position = 4320,
2888
+ Val = TabStopValues.Left,
2889
+ Leader = TabStopLeaderCharValues.Heavy
2890
+ )
2891
+ );
2892
+
2893
+ // Tab with middle dot leader
2894
+ ParagraphProperties middleDotLeaderTab = new ParagraphProperties(
2895
+ new Tabs(
2896
+ new TabStop
2897
+ {
2898
+ Position = 4320,
2899
+ Val = TabStopValues.Left,
2900
+ Leader = TabStopLeaderCharValues.MiddleDot
2901
+ }
2902
+ )
2903
+ );
2904
+
2905
+ // CENTER TAB (text centered at tab position)
2906
+ ParagraphProperties centerTab = new ParagraphProperties(
2907
+ new Tabs(
2908
+ new TabStop { Position = 4320, Val = TabStopValues.Center }
2909
+ )
2910
+ );
2911
+
2912
+ // RIGHT TAB (text right-aligned at tab position)
2913
+ ParagraphProperties rightTab = new ParagraphProperties(
2914
+ new Tabs(
2915
+ new TabStop { Position = 5760, Val = TabStopValues.Right }
2916
+ )
2917
+ );
2918
+
2919
+ // DECIMAL TAB (aligns on decimal point)
2920
+ ParagraphProperties decimalTab = new ParagraphProperties(
2921
+ new Tabs(
2922
+ new TabStop
2923
+ {
2924
+ Position = 5040, // 3.5 inches
2925
+ Val = TabStopValues.Decimal,
2926
+ TabChar = '.' // Align on period (or specify comma for European)
2927
+ }
2928
+ )
2929
+ );
2930
+
2931
+ // BAR TAB (vertical bar at tab position)
2932
+ ParagraphProperties barTab = new ParagraphProperties(
2933
+ new Tabs(
2934
+ new TabStop { Position = 2880, Val = TabStopValues.Bar }
2935
+ )
2936
+ );
2937
+
2938
+ // CLEAR TAB (removes inherited tab at this position)
2939
+ ParagraphProperties clearTab = new ParagraphProperties(
2940
+ new Tabs(
2941
+ new TabStop { Position = 1440, Val = TabStopValues.Clear }
2942
+ )
2943
+ );
2944
+
2945
+ // TAB STOP LEADER VALUES (Leader property):
2946
+ // None = no leader
2947
+ // Dot = ....... (dots)
2948
+ // Dash = ------- (dashes)
2949
+ // Underscore = _______ (underscores)
2950
+ // Heavy = ═══════ (heavy line)
2951
+ // MiddleDot = ········ (centered dots, European style)
2952
+
2953
+ // ===========================================================================
2954
+ // 4.9 SUPPRESS AUTO HYPHENS (suppressAutoHyphens)
2955
+ // ===========================================================================
2956
+ // When true, Word won't auto-hyphenate this paragraph
2957
+
2958
+ // Prevent auto-hyphenation
2959
+ ParagraphProperties noAutoHyphens = new ParagraphProperties(
2960
+ new SuppressAutoHyphens()
2961
+ );
2962
+
2963
+ // Allow hyphenation (default) — explicit
2964
+ ParagraphProperties allowAutoHyphens = new ParagraphProperties(
2965
+ new SuppressAutoHyphens { Val = OnOffValueValues.Off }
2966
+ );
2967
+
2968
+ // ===========================================================================
2969
+ // 4.10 NUMBERING PROPERTIES (numPr)
2970
+ // ===========================================================================
2971
+ // numPr links a paragraph to a numbering definition (bullets or lists)
2972
+
2973
+ // Simple bullet list item
2974
+ Paragraph bulletItem = new Paragraph(
2975
+ new ParagraphProperties(
2976
+ new NumberingProperties(
2977
+ new NumberingLevelReference { Val = 0 }, // Level 0 (top-level)
2978
+ new NumberingId { Val = 1 } // References numbering definition
2979
+ ),
2980
+ new Indentation { Left = "720", Hanging = "360" } // Standard hanging indent
2981
+ ),
2982
+ new Run(new Text("First bullet item"))
2983
+ );
2984
+
2985
+ // Numbered list item
2986
+ Paragraph numberedItem = new Paragraph(
2987
+ new ParagraphProperties(
2988
+ new NumberingProperties(
2989
+ new NumberingLevelReference { Val = 0 },
2990
+ new NumberingId { Val = 2 }
2991
+ ),
2992
+ new Indentation { Left = "720", Hanging = "360" }
2993
+ ),
2994
+ new Run(new Text("First numbered item"))
2995
+ );
2996
+
2997
+ // Multi-level list item (level 2)
2998
+ Paragraph level2Item = new Paragraph(
2999
+ new ParagraphProperties(
3000
+ new NumberingProperties(
3001
+ new NumberingLevelReference { Val = 2 }, // Level 2 (sub-sub-item)
3002
+ new NumberingId { Val = 1 }
3003
+ ),
3004
+ new Indentation { Left = "1440", Hanging = "360" } // Deeper indent
3005
+ ),
3006
+ new Run(new Text("Sub-item under sub-item"))
3007
+ );
3008
+
3009
+ // Restart numbering at this paragraph
3010
+ Paragraph restartNumberedItem = new Paragraph(
3011
+ new ParagraphProperties(
3012
+ new NumberingProperties(
3013
+ new NumberingLevelReference { Val = 0 },
3014
+ new NumberingId { Val = 3 },
3015
+ new NumberingRestart { Val = NumberingRestartValues.Restart } // Restart
3016
+ ),
3017
+ new Indentation { Left = "720", Hanging = "360" }
3018
+ ),
3019
+ new Run(new Text("Item 1 (restarted)"))
3020
+ );
3021
+
3022
+ // Continue numbering (default)
3023
+ Paragraph continueNumberedItem = new Paragraph(
3024
+ new ParagraphProperties(
3025
+ new NumberingProperties(
3026
+ new NumberingLevelReference { Val = 0 },
3027
+ new NumberingId { Val = 3 },
3028
+ new NumberingRestart { Val = NumberingRestartValues.Continuous } // Continue
3029
+ ),
3030
+ new Indentation { Left = "720", Hanging = "360" }
3031
+ ),
3032
+ new Run(new Text("Item 4 (continued)"))
3033
+ );
3034
+
3035
+ // ===========================================================================
3036
+ // 4.11 PARAGRAPH STYLE (pStyle)
3037
+ // ===========================================================================
3038
+ // pStyle references a paragraph style by ID
3039
+
3040
+ // Apply Heading1 style
3041
+ ParagraphProperties styledPara = new ParagraphProperties(
3042
+ new ParagraphStyleId { Val = "Heading1" }
3043
+ );
3044
+
3045
+ // Apply custom style
3046
+ ParagraphProperties customStyledPara = new ParagraphProperties(
3047
+ new ParagraphStyleId { Val = "MyCustomStyle" }
3048
+ );
3049
+
3050
+ // Default paragraph style (Normal)
3051
+ ParagraphProperties normalPara = new ParagraphProperties(
3052
+ new ParagraphStyleId { Val = "Normal" }
3053
+ );
3054
+
3055
+ // ===========================================================================
3056
+ // 4.12 BIDIRECTIONAL (BiDi, rtl)
3057
+ // ===========================================================================
3058
+ // BiDi enables right-to-left paragraph layout for Arabic/Hebrew
3059
+
3060
+ // Right-to-left paragraph
3061
+ ParagraphProperties rtlParagraph = new ParagraphProperties(
3062
+ new BiDi()
3063
+ );
3064
+
3065
+ // Left-to-right (default) — explicit
3066
+ ParagraphProperties ltrParagraph = new ParagraphProperties(
3067
+ new BiDi { Val = OnOffValueValues.Off }
3068
+ );
3069
+
3070
+ // When BiDi is on:
3071
+ // - Text flows right-to-left
3072
+ // - Justification defaults to right
3073
+ // - List numbering appears on the right
3074
+
3075
+ // ===========================================================================
3076
+ // 4.13 CONTEXTUAL SPACING (contextualSpacing)
3077
+ // ===========================================================================
3078
+ // When true, suppresses space between paragraphs when they share the same style
3079
+ // Useful for headings followed by body text within the same style
3080
+
3081
+ // Enable contextual spacing (suppress space between same-style paragraphs)
3082
+ ParagraphProperties contextualSpacing = new ParagraphProperties(
3083
+ new ContextualSpacing()
3084
+ );
3085
+
3086
+ // Disable contextual spacing (normal space between all paragraphs)
3087
+ ParagraphProperties noContextualSpacing = new ParagraphProperties(
3088
+ new ContextualSpacing { Val = OnOffValueValues.Off }
3089
+ );
3090
+
3091
+ // ===========================================================================
3092
+ // 4.14 MIRROR IN DENTS (mirrorIndents)
3093
+ // ===========================================================================
3094
+ // When enabled, Left/Right indents are mirrored for odd/even pages
3095
+ // (left indent on even pages becomes right indent on odd pages)
3096
+ // Used for book-style printing with binding margin
3097
+
3098
+ // Enable mirror indents
3099
+ ParagraphProperties mirrorIndents = new ParagraphProperties(
3100
+ new MirrorIndents()
3101
+ );
3102
+
3103
+ // Disable mirror indents (default)
3104
+ ParagraphProperties noMirrorIndents = new ParagraphProperties(
3105
+ new MirrorIndents { Val = OnOffValueValues.Off }
3106
+ );
3107
+
3108
+ // ===========================================================================
3109
+ // 4.15 TEXT DIRECTION (textDirection)
3110
+ // ===========================================================================
3111
+ // Controls text flow direction within the paragraph
3112
+
3113
+ // Left-to-right (default)
3114
+ ParagraphProperties ltrTextFlow = new ParagraphProperties(
3115
+ new TextDirection { Val = TextDirectionValues.LeftToRight }
3116
+ );
3117
+
3118
+ // Right-to-left
3119
+ ParagraphProperties rtlTextFlow = new ParagraphProperties(
3120
+ new TextDirection { Val = TextDirectionValues.RightToLeft }
3121
+ );
3122
+
3123
+ // Top-to-bottom (vertical, common in East Asian documents)
3124
+ ParagraphProperties verticalTextFlow = new ParagraphProperties(
3125
+ new TextDirection { Val = TextDirectionValues.TopToBottom }
3126
+ );
3127
+
3128
+ // Bottom-to-top (vertical rotated 180°)
3129
+ ParagraphProperties bottomToTopTextFlow = new ParagraphProperties(
3130
+ new TextDirection { Val = TextDirectionValues.BottomToTop }
3131
+ );
3132
+
3133
+ // Left-to-right rotated (90° clockwise)
3134
+ ParagraphProperties leftToRightRotated = new ParagraphProperties(
3135
+ new TextDirection { Val = TextDirectionValues.LeftToRightRotated }
3136
+ );
3137
+
3138
+ // Right-to-left rotated (90° counter-clockwise)
3139
+ ParagraphProperties rightToLeftRotated = new ParagraphProperties(
3140
+ new TextDirection { Val = TextDirectionValues.RightToLeftRotated }
3141
+ );
3142
+
3143
+ // ===========================================================================
3144
+ // 4.16 SNAP TO GRID (snapToGrid)
3145
+ // ===========================================================================
3146
+ // Aligns paragraph to document grid for consistent vertical spacing
3147
+
3148
+ // Enable snap to grid
3149
+ ParagraphProperties snapToGridPara = new ParagraphProperties(
3150
+ new SnapToGrid()
3151
+ );
3152
+
3153
+ // Disable snap to grid
3154
+ ParagraphProperties noSnapToGridPara = new ParagraphProperties(
3155
+ new SnapToGrid { Val = OnOffValueValues.Off }
3156
+ );
3157
+
3158
+ // ===========================================================================
3159
+ // 4.17 TEXT ALIGNMENT (textAlignment)
3160
+ // ===========================================================================
3161
+ // Vertical alignment of text within a line box (rarely used)
3162
+ // Default is Auto (baseline)
3163
+
3164
+ // Baseline alignment (default)
3165
+ ParagraphProperties baselineAlign = new ParagraphProperties(
3166
+ new TextAlignment { Val = VerticalTextAlignmentValues.Auto }
3167
+ );
3168
+
3169
+ // Top alignment
3170
+ ParagraphProperties topAlign = new ParagraphProperties(
3171
+ new TextAlignment { Val = VerticalTextAlignmentValues.Top }
3172
+ );
3173
+
3174
+ // Center alignment
3175
+ ParagraphProperties centerVerticalAlign = new ParagraphProperties(
3176
+ new TextAlignment { Val = VerticalTextAlignmentValues.Center }
3177
+ );
3178
+
3179
+ // Bottom alignment
3180
+ ParagraphProperties bottomAlign = new ParagraphProperties(
3181
+ new TextAlignment { Val = VerticalTextAlignmentValues.Bottom }
3182
+ );
3183
+
3184
+ // Baseline alignment (explicit)
3185
+ ParagraphProperties baselineAlignExplicit = new ParagraphProperties(
3186
+ new TextAlignment { Val = VerticalTextAlignmentValues.Baseline }
3187
+ );
3188
+
3189
+ // ===========================================================================
3190
+ // 4.18 DIV ID (divId)
3191
+ // ===========================================================================
3192
+ // Associates paragraph with a div for HTML/CSS mapping (很少使用)
3193
+ // Used when importing/exporting HTML content
3194
+
3195
+ ParagraphProperties divIdPara = new ParagraphProperties(
3196
+ new DivId { Val = "myDiv123" }
3197
+ );
3198
+
3199
+ // ===========================================================================
3200
+ // 4.19 CNF STYLE (cnfStyle)
3201
+ // ===========================================================================
3202
+ // Conditional formatting style index (used by Word for table of contents,
3203
+ // styles pane grouping, etc.) — typically set automatically by Word
3204
+
3205
+ ParagraphProperties cnfStylePara = new ParagraphProperties(
3206
+ new CnfStyle { Val = 1 } // Index into style's cnfStyle definitions
3207
+ );
3208
+
3209
+ // ===========================================================================
3210
+ // 4.20 SECTION PROPERTIES IN PARAGRAPH (sectPr)
3211
+ // ===========================================================================
3212
+ // Section properties can appear INSIDE a paragraph to create a section break
3213
+ // BEFORE that paragraph. This is how you have different page layouts
3214
+ // in different parts of the document.
3215
+
3216
+ // Section break with continuous layout
3217
+ Paragraph continuousSectionBreak = new Paragraph(
3218
+ new ParagraphProperties(
3219
+ new SectionProperties(
3220
+ new SectionType { Val = SectionMarkValues.Continuous }
3221
+ )
3222
+ )
3223
+ );
3224
+
3225
+ // Section break starting new page
3226
+ Paragraph newPageSectionBreak = new Paragraph(
3227
+ new ParagraphProperties(
3228
+ new SectionProperties(
3229
+ new SectionType { Val = SectionMarkValues.NextPage }
3230
+ )
3231
+ )
3232
+ );
3233
+
3234
+ // Section break with even page
3235
+ Paragraph evenPageSectionBreak = new Paragraph(
3236
+ new ParagraphProperties(
3237
+ new SectionProperties(
3238
+ new SectionType { Val = SectionMarkValues.EvenPage }
3239
+ )
3240
+ )
3241
+ );
3242
+
3243
+ // Section break with odd page
3244
+ Paragraph oddPageSectionBreak = new Paragraph(
3245
+ new ParagraphProperties(
3246
+ new SectionProperties(
3247
+ new SectionType { Val = SectionMarkValues.OddPage }
3248
+ )
3249
+ )
3250
+ );
3251
+
3252
+ // Section with custom page size
3253
+ Paragraph customSectionPara = new Paragraph(
3254
+ new ParagraphProperties(
3255
+ new SectionProperties(
3256
+ new PageSize { Width = 12240u, Height = 15840u }, // Letter
3257
+ new PageMargin
3258
+ {
3259
+ Top = 1440,
3260
+ Bottom = 1440,
3261
+ Left = 1440u,
3262
+ Right = 1440u
3263
+ }
3264
+ )
3265
+ )
3266
+ );
3267
+
3268
+ // ===========================================================================
3269
+ // 4.21 COMBINED PARAGRAPH FORMATTING EXAMPLE
3270
+ // ===========================================================================
3271
+ // Complete paragraph properties combining many options
3272
+
3273
+ ParagraphProperties complexParaProps = new ParagraphProperties(
3274
+ // Style reference
3275
+ new ParagraphStyleId { Val = "Normal" },
3276
+
3277
+ // Keep options
3278
+ new KeepNext(),
3279
+ new KeepLines(),
3280
+ new WidowControl(),
3281
+
3282
+ // Spacing
3283
+ new SpacingBetweenLines
3284
+ {
3285
+ Before = "240",
3286
+ After = "200",
3287
+ Line = "276",
3288
+ LineRule = LineSpacingRuleValues.Auto
3289
+ },
3290
+
3291
+ // Indentation
3292
+ new Indentation
3293
+ {
3294
+ Left = "0",
3295
+ Right = "0",
3296
+ FirstLine = "0",
3297
+ Hanging = "0"
3298
+ },
3299
+
3300
+ // Alignment
3301
+ new Justification { Val = JustificationValues.Left },
3302
+
3303
+ // Border (bottom line)
3304
+ new ParagraphBorders(
3305
+ new BottomBorder
3306
+ {
3307
+ Val = BorderValues.Single,
3308
+ Size = 4,
3309
+ Color = "CCCCCC",
3310
+ Space = 4
3311
+ }
3312
+ ),
3313
+
3314
+ // Shading
3315
+ new Shading
3316
+ {
3317
+ Val = ShadingPatternValues.Clear,
3318
+ Color = "auto",
3319
+ Fill = "auto"
3320
+ },
3321
+
3322
+ // Tabs
3323
+ new Tabs(
3324
+ new TabStop { Position = 1440, Val = TabStopValues.Left },
3325
+ new TabStop { Position = 2880, Val = TabStopValues.Center, Leader = TabStopLeaderCharValues.Dot }
3326
+ ),
3327
+
3328
+ // Outline level (for TOC)
3329
+ new OutlineLevel { Val = 0 },
3330
+
3331
+ // Bidirectional
3332
+ new BiDi { Val = OnOffValueValues.Off },
3333
+
3334
+ // Contextual spacing
3335
+ new ContextualSpacing(),
3336
+
3337
+ // Snap to grid
3338
+ new SnapToGrid(),
3339
+
3340
+ // Suppress auto hyphens
3341
+ new SuppressAutoHyphens { Val = OnOffValueValues.Off }
3342
+ );
3343
+
3344
+ // ===========================================================================
3345
+ // 4.22 APPLYING PARAGRAPH PROPERTIES
3346
+ // ===========================================================================
3347
+ // ParagraphProperties can be applied in multiple ways:
3348
+
3349
+ // Method 1: Inline in Paragraph (direct formatting)
3350
+ Paragraph inlineParaProps = new Paragraph(
3351
+ new ParagraphProperties(
3352
+ new Justification { Val = JustificationValues.Center },
3353
+ new SpacingBetweenLines { After = "200" }
3354
+ ),
3355
+ new Run(new Text("Centered paragraph with space after"))
3356
+ );
3357
+
3358
+ // Method 2: Via ParagraphStyleId (paragraph style)
3359
+ Paragraph styledParagraph = new Paragraph(
3360
+ new ParagraphProperties(
3361
+ new ParagraphStyleId { Val = "Heading1" }
3362
+ ),
3363
+ new Run(new Text("This is Heading 1"))
3364
+ );
3365
+
3366
+ // Method 3: In Style definition (style-level)
3367
+ Style bodyTextStyle = new Style(
3368
+ new StyleName { Val = "BodyText" },
3369
+ new BasedOn { Val = "Normal" },
3370
+ new StyleParagraphProperties(
3371
+ new Justification { Val = JustificationValues.Both }, // Justify
3372
+ new SpacingBetweenLines { After = "160", Line = "276", LineRule = LineSpacingRuleValues.Auto },
3373
+ new Indentation { FirstLine = "568" } // First line indent 0.5"
3374
+ ),
3375
+ new StyleRunProperties(
3376
+ new FontSize { Val = "22" }
3377
+ )
3378
+ )
3379
+ { Type = StyleValues.Paragraph, StyleId = "BodyText" };
3380
+
3381
+ // Method 4: Combination (style + direct overrides)
3382
+ Paragraph mixedParaProps = new Paragraph(
3383
+ new ParagraphProperties(
3384
+ new ParagraphStyleId { Val = "BodyText" }, // Apply style
3385
+ new Justification { Val = JustificationValues.Left } // Override justification
3386
+ ),
3387
+ new Run(new Text("Body text style but left-aligned"))
3388
+ );
3389
+
3390
+ // ===========================================================================
3391
+ // 4.23 COMMON PATTERNS
3392
+ // ===========================================================================
3393
+ // Heading paragraph (with style + keep options)
3394
+ Paragraph headingPara = new Paragraph(
3395
+ new ParagraphProperties(
3396
+ new ParagraphStyleId { Val = "Heading1" },
3397
+ new KeepNext(),
3398
+ new KeepLines(),
3399
+ new SpacingBetweenLines { Before = "480", After = "120" },
3400
+ new OutlineLevel { Val = 0 }
3401
+ ),
3402
+ new Run(new Text("Chapter One"))
3403
+ );
3404
+
3405
+ // Quote paragraph (indented, italic)
3406
+ Paragraph quotePara = new Paragraph(
3407
+ new ParagraphProperties(
3408
+ new Indentation { Left = "1440", Right = "1440" },
3409
+ new SpacingBetweenLines { Before = "240", After = "240" },
3410
+ new ParagraphBorders(
3411
+ new LeftBorder
3412
+ {
3413
+ Val = BorderValues.Single,
3414
+ Size = 24,
3415
+ Color = "4472C4",
3416
+ Space = 8
3417
+ }
3418
+ )
3419
+ ),
3420
+ new Run(
3421
+ new RunProperties(new Italic()),
3422
+ new Text("To be, or not to be, that is the question."))
3423
+ );
3424
+
3425
+ // List item paragraph (hanging indent pattern)
3426
+ Paragraph listItemPara = new Paragraph(
3427
+ new ParagraphProperties(
3428
+ new NumberingProperties(
3429
+ new NumberingLevelReference { Val = 0 },
3430
+ new NumberingId { Val = 1 }
3431
+ ),
3432
+ new Indentation { Left = "720", Hanging = "360" }
3433
+ ),
3434
+ new Run(new Text("• List item text"))
3435
+ );
3436
+
3437
+ // Block quote / callout (background, left border)
3438
+ Paragraph blockQuotePara = new Paragraph(
3439
+ new ParagraphProperties(
3440
+ new Indentation { Left = "720" },
3441
+ new Shading
3442
+ {
3443
+ Val = ShadingPatternValues.Clear,
3444
+ Fill = "F5F5F5"
3445
+ },
3446
+ new ParagraphBorders(
3447
+ new LeftBorder
3448
+ {
3449
+ Val = BorderValues.Single,
3450
+ Size = 12,
3451
+ Color = "999999",
3452
+ Space = 8
3453
+ }
3454
+ ),
3455
+ new SpacingBetweenLines { Before = "120", After = "120" }
3456
+ ),
3457
+ new Run(new Text("Block quote text"))
3458
+ );
3459
+
3460
+ // Caption (centered, small text, below figure)
3461
+ Paragraph captionPara = new Paragraph(
3462
+ new ParagraphProperties(
3463
+ new Justification { Val = JustificationValues.Center },
3464
+ new SpacingBetweenLines { Before = "0", After = "240" },
3465
+ new ParagraphStyleId { Val = "Caption" }
3466
+ ),
3467
+ new Run(
3468
+ new RunProperties(
3469
+ new FontSize { Val = "20" }, // 10pt
3470
+ new Italic()
3471
+ ),
3472
+ new Text("Figure 1: Sample caption"))
3473
+ );
3474
+
3475
+ // Page title (large, centered, space after)
3476
+ Paragraph pageTitlePara = new Paragraph(
3477
+ new ParagraphProperties(
3478
+ new Justification { Val = JustificationValues.Center },
3479
+ new SpacingBetweenLines { After = "480" },
3480
+ new KeepLines(),
3481
+ new ParagraphBorders(
3482
+ new BottomBorder
3483
+ {
3484
+ Val = BorderValues.Single,
3485
+ Size = 4,
3486
+ Color = "000000",
3487
+ Space = 4
3488
+ }
3489
+ )
3490
+ ),
3491
+ new Run(
3492
+ new RunProperties(
3493
+ new FontSize { Val = "56" }, // 28pt
3494
+ new Bold()
3495
+ ),
3496
+ new Text("Document Title"))
3497
+ );
3498
+
3499
+ // Signature line (right-aligned, with tab for signature)
3500
+ Paragraph signatureLinePara = new Paragraph(
3501
+ new ParagraphProperties(
3502
+ new Tabs(
3503
+ new TabStop { Position = 5760, Val = TabStopValues.Right } // 4" right tab
3504
+ )
3505
+ ),
3506
+ new Run(new Text("Name: ") { Space = SpaceProcessingModeValues.Preserve }),
3507
+ new Run(new TabChar()),
3508
+ new Run(new Text("Date: ") { Space = SpaceProcessingModeValues.Preserve }),
3509
+ new Run(new TabChar()),
3510
+ new Run(new Text("Signature: ") { Space = SpaceProcessingModeValues.Preserve })
3511
+ );
3512
+
3513
+ // Bibliography entry (hanging indent, single-spaced)
3514
+ Paragraph bibliographyEntry = new Paragraph(
3515
+ new ParagraphProperties(
3516
+ new Indentation { Left = "720", Hanging = "720" },
3517
+ new SpacingBetweenLines { Line = "240", LineRule = LineSpacingRuleValues.Auto },
3518
+ new Bibliography()
3519
+ ),
3520
+ new Run(new Text("Smith, J. (2024). The Art of OpenXML. New York: Publisher."))
3521
+ );
3522
+
3523
+ // ===========================================================================
3524
+ // 4.24 UNIT SYSTEM QUICK REFERENCE
3525
+ // ===========================================================================
3526
+ // DXA (Twentieths of a DXA / Twips):
3527
+ // 1 inch = 1440 DXA
3528
+ // 1 cm ≈ 567 DXA
3529
+ // 1 pt = 20 DXA
3530
+ // Used for: margins, indents, spacing, tab stops, borders
3531
+ //
3532
+ // Half-Points (Font Size):
3533
+ // 24 = 12pt
3534
+ // 22 = 11pt
3535
+ // 20 = 10pt
3536
+ // Used for: FontSize.Val
3537
+ //
3538
+ // Points (pt):
3539
+ // Used for: border widths, some line spacing values
3540
+ //
3541
+ // EMU (English Metric Units):
3542
+ // 1 inch = 914400 EMU
3543
+ // Used for: drawing objects, images, shapes
3544
+ //
3545
+ // COMMON DXA VALUES:
3546
+ // 720 = 0.5 inch
3547
+ // 1440 = 1 inch
3548
+ // 2160 = 1.5 inches
3549
+ // 2880 = 2 inches
3550
+ // 4320 = 3 inches
3551
+ // 5760 = 4 inches
3552
+ // 8640 = 6 inches
3553
+ ```
3554
+
3555
+ ---
3556
+
3557
+ ## Appendix A: Complete Working Example
3558
+
3559
+ ```csharp
3560
+ // =============================================================================
3561
+ // COMPLETE WORKING EXAMPLE: BUSINESS REPORT
3562
+ // =============================================================================
3563
+ // This example demonstrates a complete, professional document with
3564
+ // all concepts covered in this encyclopedia.
3565
+
3566
+ using DocumentFormat.OpenXml;
3567
+ using DocumentFormat.OpenXml.Packaging;
3568
+ using DocumentFormat.OpenXml.Wordprocessing;
3569
+
3570
+ namespace OpenXmlExamples;
3571
+
3572
+ public static class BusinessReportGenerator
3573
+ {
3574
+ public static void Generate(string outputPath)
3575
+ {
3576
+ using var doc = WordprocessingDocument.Create(
3577
+ outputPath,
3578
+ WordprocessingDocumentType.Document);
3579
+
3580
+ var mainPart = doc.MainDocumentPart!;
3581
+ mainPart.Document = new Document(new Body());
3582
+ var body = mainPart.Document.Body!;
3583
+
3584
+ // Add all parts
3585
+ AddStyles(mainPart);
3586
+ AddNumbering(mainPart);
3587
+ AddSettings(mainPart);
3588
+ AddTheme(mainPart);
3589
+ AddHeadersAndFooters(mainPart);
3590
+
3591
+ // Add content
3592
+ AddTitle(body);
3593
+ AddTableOfContents(body);
3594
+ AddExecutiveSummary(body);
3595
+ AddSection(body, "Introduction", @"
3596
+ This is the introduction section of the business report.
3597
+ It contains multiple paragraphs with various formatting.");
3598
+ AddSection(body, "Methodology", @"
3599
+ Our methodology section describes the approach taken.
3600
+ Bulleted lists are used for key points:");
3601
+ AddBulletPoints(body, new[]
3602
+ {
3603
+ "First methodology point",
3604
+ "Second methodology point",
3605
+ "Third methodology point with more text to demonstrate wrapping"
3606
+ });
3607
+ AddSection(body, "Results", @"
3608
+ The results section presents data in tables:");
3609
+ AddSampleTable(body);
3610
+ AddSection(body, "Conclusion", @"
3611
+ In conclusion, this report demonstrates the capabilities of the OpenXML SDK.
3612
+ The formatting options are comprehensive and allow for professional document generation.");
3613
+
3614
+ // Section properties (must be last)
3615
+ body.Append(CreateSectionProperties(mainPart));
3616
+
3617
+ mainPart.Document.Save();
3618
+ }
3619
+
3620
+ private static void AddStyles(MainDocumentPart mainPart)
3621
+ {
3622
+ var stylesPart = mainPart.AddNewPart<StyleDefinitionsPart>();
3623
+ var styles = CreateBusinessStyles();
3624
+ stylesPart.Styles = styles;
3625
+ stylesPart.Styles.Save();
3626
+ }
3627
+
3628
+ private static Styles CreateBusinessStyles()
3629
+ {
3630
+ var styles = new Styles();
3631
+
3632
+ // DocDefaults
3633
+ styles.Append(new DocDefaults(
3634
+ new RunPropertiesDefault(
3635
+ new RunPropertiesBaseStyle(
3636
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
3637
+ new FontSize { Val = "22" },
3638
+ new FontSizeComplexScript { Val = "22" },
3639
+ new Languages { Val = "en-US" }
3640
+ )
3641
+ ),
3642
+ new ParagraphPropertiesDefault(
3643
+ new ParagraphPropertiesBaseStyle(
3644
+ new SpacingBetweenLines { After = "200", Line = "276", LineRule = LineSpacingRuleValues.Auto }
3645
+ )
3646
+ )
3647
+ ));
3648
+
3649
+ // Normal
3650
+ styles.Append(new Style(
3651
+ new StyleName { Val = "Normal" },
3652
+ new PrimaryStyle(),
3653
+ new StyleRunProperties(
3654
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
3655
+ new FontSize { Val = "22" }
3656
+ )
3657
+ )
3658
+ { Type = StyleValues.Paragraph, StyleId = "Normal", Default = true });
3659
+
3660
+ // Title
3661
+ styles.Append(new Style(
3662
+ new StyleName { Val = "Title" },
3663
+ new BasedOn { Val = "Normal" },
3664
+ new NextParagraphStyle { Val = "Normal" },
3665
+ new PrimaryStyle(),
3666
+ new QuickStyle(),
3667
+ new StyleParagraphProperties(
3668
+ new Justification { Val = JustificationValues.Center },
3669
+ new SpacingBetweenLines { After = "300" },
3670
+ new KeepNext(),
3671
+ new KeepLines()
3672
+ ),
3673
+ new StyleRunProperties(
3674
+ new RunFonts { Ascii = "Calibri Light", HighAnsi = "Calibri Light" },
3675
+ new FontSize { Val = "56" },
3676
+ new Bold(),
3677
+ new Color { Val = "1F497D" }
3678
+ )
3679
+ )
3680
+ { Type = StyleValues.Paragraph, StyleId = "Title" });
3681
+
3682
+ // Heading 1
3683
+ styles.Append(new Style(
3684
+ new StyleName { Val = "heading 1" },
3685
+ new BasedOn { Val = "Normal" },
3686
+ new NextParagraphStyle { Val = "Normal" },
3687
+ new PrimaryStyle(),
3688
+ new QuickStyle(),
3689
+ new StyleParagraphProperties(
3690
+ new KeepNext(),
3691
+ new KeepLines(),
3692
+ new SpacingBetweenLines { Before = "480", After = "120" },
3693
+ new OutlineLevel { Val = 0 },
3694
+ new ParagraphBorders(
3695
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "4472C4", Space = 4 }
3696
+ )
3697
+ ),
3698
+ new StyleRunProperties(
3699
+ new RunFonts { Ascii = "Calibri Light", HighAnsi = "Calibri Light" },
3700
+ new FontSize { Val = "48" },
3701
+ new Bold(),
3702
+ new Color { Val = "1F497D" }
3703
+ )
3704
+ )
3705
+ { Type = StyleValues.Paragraph, StyleId = "Heading1" });
3706
+
3707
+ // Heading 2
3708
+ styles.Append(new Style(
3709
+ new StyleName { Val = "heading 2" },
3710
+ new BasedOn { Val = "Normal" },
3711
+ new NextParagraphStyle { Val = "Normal" },
3712
+ new PrimaryStyle(),
3713
+ new QuickStyle(),
3714
+ new StyleParagraphProperties(
3715
+ new KeepNext(),
3716
+ new SpacingBetweenLines { Before = "240", After = "120" },
3717
+ new OutlineLevel { Val = 1 }
3718
+ ),
3719
+ new StyleRunProperties(
3720
+ new FontSize { Val = "32" },
3721
+ new Bold(),
3722
+ new Color { Val = "2F5496" }
3723
+ )
3724
+ )
3725
+ { Type = StyleValues.Paragraph, StyleId = "Heading2" });
3726
+
3727
+ return styles;
3728
+ }
3729
+
3730
+ private static void AddNumbering(MainDocumentPart mainPart)
3731
+ {
3732
+ var numberingPart = mainPart.AddNewPart<NumberingDefinitionsPart>();
3733
+ var numbering = new Numbering();
3734
+
3735
+ var abstractNum = new AbstractNum { AbstractNumberId = 1 };
3736
+ abstractNum.Append(new Level(
3737
+ new StartNumberingValue { Val = 1 },
3738
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
3739
+ new LevelText { Val = "•" },
3740
+ new LevelJustification { Val = LevelJustificationValues.Left },
3741
+ new PreviousParagraphProperties(
3742
+ new Indentation { Left = "720", Hanging = "360" })
3743
+ )
3744
+ { LevelIndex = 0 });
3745
+
3746
+ numbering.Append(abstractNum);
3747
+ numbering.Append(new NumberingInstance(
3748
+ new AbstractNumId { Val = 1 }
3749
+ )
3750
+ { NumberID = 1 });
3751
+
3752
+ numberingPart.Numbering = numbering;
3753
+ numberingPart.Numbering.Save();
3754
+ }
3755
+
3756
+ private static void AddSettings(MainDocumentPart mainPart)
3757
+ {
3758
+ var settingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
3759
+ settingsPart.Settings = new Settings(
3760
+ new Zoom { Val = "100", Percent = true },
3761
+ new DefaultTabStop { Val = 720 },
3762
+ new CharacterSpacingControl { Val = CharacterSpacingValues.CompressPunctuation }
3763
+ );
3764
+ settingsPart.Settings.Save();
3765
+ }
3766
+
3767
+ private static void AddTheme(MainDocumentPart mainPart)
3768
+ {
3769
+ var themePart = mainPart.AddNewPart<ThemePart>();
3770
+ themePart.Theme = new Theme(
3771
+ new ThemeElements(
3772
+ new ColorScheme(
3773
+ new Dark1Color(new Color { Val = "000000" }),
3774
+ new Light1Color(new Color { Val = "FFFFFF" }),
3775
+ new Accent1Color(new Color { Val = "4472C4" }),
3776
+ new Accent2Color(new Color { Val = "C0504D" }),
3777
+ new Accent3Color(new Color { Val = "9BBB59" }),
3778
+ new Accent4Color(new Color { Val = "8064A2" }),
3779
+ new Accent5Color(new Color { Val = "4BACC6" }),
3780
+ new Accent6Color(new Color { Val = "F79646" })
3781
+ ),
3782
+ new FontScheme(
3783
+ new MajorFont { Val = "Calibri Light" },
3784
+ new MinorFont { Val = "Calibri" }
3785
+ )
3786
+ ),
3787
+ new ThemeName { Val = "Office Theme" }
3788
+ );
3789
+ themePart.Theme.Save();
3790
+ }
3791
+
3792
+ private static void AddHeadersAndFooters(MainDocumentPart mainPart)
3793
+ {
3794
+ var headerPart = mainPart.AddNewPart<HeaderPart>();
3795
+ headerPart.Header = new Header(
3796
+ new Paragraph(
3797
+ new ParagraphProperties(new Justification { Val = JustificationValues.Right }),
3798
+ new Run(
3799
+ new RunProperties(new RunFonts { Ascii = "Calibri Light" }, new Italic(), new FontSize { Val = "18" }),
3800
+ new Text("Business Report"))
3801
+ ));
3802
+ var headerId = mainPart.GetIdOfPart(headerPart);
3803
+
3804
+ var footerPart = mainPart.AddNewPart<FooterPart>();
3805
+ footerPart.Footer = new Footer(
3806
+ new Paragraph(
3807
+ new ParagraphProperties(new Justification { Val = JustificationValues.Center }),
3808
+ new Run(new Text("Page ") { Space = SpaceProcessingModeValues.Preserve }),
3809
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
3810
+ new Run(new FieldCode(" PAGE ") { Space = SpaceProcessingModeValues.Preserve }),
3811
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End }),
3812
+ new Run(new Text(" of ") { Space = SpaceProcessingModeValues.Preserve }),
3813
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
3814
+ new Run(new FieldCode(" NUMPAGES ") { Space = SpaceProcessingModeValues.Preserve }),
3815
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End })
3816
+ ));
3817
+ var footerId = mainPart.GetIdOfPart(footerPart);
3818
+
3819
+ // Store IDs for later use
3820
+ mainPart.Document.Body!.Append(new Paragraph()); // Placeholder for sectPr
3821
+ }
3822
+
3823
+ private static void AddTitle(Body body)
3824
+ {
3825
+ body.Append(new Paragraph(
3826
+ new ParagraphProperties(new ParagraphStyleId { Val = "Title" }),
3827
+ new Run(new Text("Business Report"))
3828
+ ));
3829
+
3830
+ body.Append(new Paragraph(
3831
+ new ParagraphProperties(new ParagraphStyleId { Val = "Subtitle" }),
3832
+ new Run(new Text("Quarterly Performance Analysis"))
3833
+ ));
3834
+
3835
+ body.Append(new Paragraph(
3836
+ new ParagraphProperties(new SpacingBetweenLines { After = "400" }),
3837
+ new Run(
3838
+ new RunProperties(new Color { Val = "666666" }),
3839
+ new Text("March 2026"))
3840
+ ));
3841
+ }
3842
+
3843
+ private static void AddTableOfContents(Body body)
3844
+ {
3845
+ body.Append(new Paragraph(
3846
+ new ParagraphProperties(new ParagraphStyleId { Val = "Heading1" }),
3847
+ new Run(new Text("Table of Contents"))
3848
+ ));
3849
+
3850
+ var tocPara = new Paragraph();
3851
+ tocPara.Append(new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }));
3852
+ tocPara.Append(new Run(new FieldCode(" TOC \\o \"1-2\" \\h \\z \\u ") { Space = SpaceProcessingModeValues.Preserve }));
3853
+ tocPara.Append(new Run(new FieldChar { FieldCharType = FieldCharValues.Separate }));
3854
+ tocPara.Append(new Run(new Text("Update field to generate Table of Contents")));
3855
+ tocPara.Append(new Run(new FieldChar { FieldCharType = FieldCharValues.End }));
3856
+ body.Append(tocPara);
3857
+
3858
+ body.Append(new Paragraph(new Run(new Break { Type = BreakValues.Page })));
3859
+ }
3860
+
3861
+ private static void AddExecutiveSummary(Body body)
3862
+ {
3863
+ body.Append(new Paragraph(
3864
+ new ParagraphProperties(new ParagraphStyleId { Val = "Heading1" }),
3865
+ new Run(new Text("Executive Summary"))
3866
+ ));
3867
+
3868
+ body.Append(new Paragraph(
3869
+ new Run(new Text("This executive summary provides a high-level overview of the quarterly performance. Key highlights include revenue growth, market expansion, and operational improvements."))
3870
+ ));
3871
+ }
3872
+
3873
+ private static void AddSection(Body body, string title, string content)
3874
+ {
3875
+ body.Append(new Paragraph(
3876
+ new ParagraphProperties(new ParagraphStyleId { Val = "Heading1" }),
3877
+ new Run(new Text(title))
3878
+ ));
3879
+
3880
+ body.Append(new Paragraph(
3881
+ new Run(new Text(content))
3882
+ ));
3883
+ }
3884
+
3885
+ private static void AddBulletPoints(Body body, string[] points)
3886
+ {
3887
+ foreach (var point in points)
3888
+ {
3889
+ body.Append(new Paragraph(
3890
+ new ParagraphProperties(
3891
+ new NumberingProperties(
3892
+ new NumberingLevelReference { Val = 0 },
3893
+ new NumberingId { Val = 1 }
3894
+ ),
3895
+ new Indentation { Left = "720", Hanging = "360" }
3896
+ ),
3897
+ new Run(new Text(point))
3898
+ ));
3899
+ }
3900
+ }
3901
+
3902
+ private static void AddSampleTable(Body body)
3903
+ {
3904
+ var table = new Table(
3905
+ new TableProperties(
3906
+ new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct },
3907
+ new TableBorders(
3908
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
3909
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
3910
+ new LeftBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
3911
+ new RightBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
3912
+ new InsideHorizontalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" },
3913
+ new InsideVerticalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" }
3914
+ ),
3915
+ new TableCellMarginDefault(
3916
+ new TopMargin { Width = "50", Type = TableWidthUnitValues.DXA },
3917
+ new BottomMargin { Width = "50", Type = TableWidthUnitValues.DXA },
3918
+ new StartMargin { Width = "100", Type = TableWidthUnitValues.DXA },
3919
+ new EndMargin { Width = "100", Type = TableWidthUnitValues.DXA }
3920
+ )
3921
+ ),
3922
+ new TableGrid(
3923
+ new GridColumn { Width = "2000" },
3924
+ new GridColumn { Width = "2000" },
3925
+ new GridColumn { Width = "2000" }
3926
+ )
3927
+ );
3928
+
3929
+ // Header row
3930
+ var headerRow = new TableRow(
3931
+ new TableRowProperties(new TableHeader()),
3932
+ CreateTableCell("Metric", bold: true),
3933
+ CreateTableCell("Q1 2026", bold: true),
3934
+ CreateTableCell("Q4 2025", bold: true)
3935
+ );
3936
+ table.Append(headerRow);
3937
+
3938
+ // Data rows
3939
+ table.Append(CreateTableRow("Revenue", "$2.5M", "$2.1M"));
3940
+ table.Append(CreateTableRow("Growth", "19%", "12%"));
3941
+ table.Append(CreateTableRow("Customers", "1,250", "1,100"));
3942
+
3943
+ body.Append(table);
3944
+ }
3945
+
3946
+ private static TableCell CreateTableCell(string text, bool bold = false)
3947
+ {
3948
+ var cell = new TableCell(
3949
+ new Paragraph(
3950
+ new Run(
3951
+ bold
3952
+ ? new RunProperties(new Bold())
3953
+ : new RunProperties(),
3954
+ new Text(text))
3955
+ )
3956
+ );
3957
+ return cell;
3958
+ }
3959
+
3960
+ private static TableRow CreateTableRow(string metric, string q1, string q4)
3961
+ {
3962
+ return new TableRow(
3963
+ CreateTableCell(metric),
3964
+ CreateTableCell(q1),
3965
+ CreateTableCell(q4)
3966
+ );
3967
+ }
3968
+
3969
+ private static SectionProperties CreateSectionProperties(MainDocumentPart mainPart)
3970
+ {
3971
+ var sectPr = new SectionProperties();
3972
+
3973
+ // Header/Footer references
3974
+ var headerPart = mainPart.HeaderParts.FirstOrDefault();
3975
+ var footerPart = mainPart.FooterParts.FirstOrDefault();
3976
+ if (headerPart != null)
3977
+ sectPr.Append(new HeaderReference { Type = HeaderFooterValues.Default, Id = mainPart.GetIdOfPart(headerPart) });
3978
+ if (footerPart != null)
3979
+ sectPr.Append(new FooterReference { Type = HeaderFooterValues.Default, Id = mainPart.GetIdOfPart(footerPart) });
3980
+
3981
+ // Page size
3982
+ sectPr.Append(new PageSize { Width = 12240u, Height = 15840u });
3983
+
3984
+ // Page margins
3985
+ sectPr.Append(new PageMargin
3986
+ {
3987
+ Top = 1440,
3988
+ Bottom = 1440,
3989
+ Left = 1440u,
3990
+ Right = 1440u,
3991
+ Header = 720u,
3992
+ Footer = 720u
3993
+ });
3994
+
3995
+ return sectPr;
3996
+ }
3997
+ }
3998
+
3999
+ // ===========================================================================
4000
+ // USAGE
4001
+ // ===========================================================================
4002
+ /*
4003
+ public static void Main(string[] args)
4004
+ {
4005
+ BusinessReportGenerator.Generate("C:\\Reports\\BusinessReport.docx");
4006
+ Console.WriteLine("Report generated successfully!");
4007
+ }
4008
+ */
4009
+ ```
4010
+
4011
+ ---
4012
+
4013
+ ## Appendix B: OpenXmlUnits Helper Class
4014
+
4015
+ ```csharp
4016
+ // =============================================================================
4017
+ // UNIT CONVERSION HELPERS
4018
+ // =============================================================================
4019
+ // Copy this class into your project for convenient unit conversions.
4020
+
4021
+ public static class OpenXmlUnits
4022
+ {
4023
+ // DXA (Twentieths of a DXA / Twips) conversions
4024
+ public static int InchesToDxa(double inches) => (int)(inches * 1440);
4025
+ public static int CmToDxa(double cm) => (int)(cm * 567.0);
4026
+ public static int PtToDxa(double pt) => (int)(pt * 20);
4027
+ public static double DxaToInches(int dxa) => dxa / 1440.0;
4028
+ public static double DxaToCm(int dxa) => dxa / 567.0;
4029
+ public static double DxaToPt(int dxa) => dxa / 20.0;
4030
+
4031
+ // EMU (English Metric Units) conversions
4032
+ public static long InchesToEmu(double inches) => (long)(inches * 914400);
4033
+ public static long CmToEmu(double cm) => (long)(cm * 360000);
4034
+ public static double EmuToInches(long emu) => emu / 914400.0;
4035
+ public static double EmuToCm(long emu) => emu / 360000.0;
4036
+
4037
+ // Half-point conversions (font sizes)
4038
+ public static int PtToHalfPt(double pt) => (int)(pt * 2);
4039
+ public static int FontSizeToSz(double ptSize) => (int)(ptSize * 2);
4040
+ public static double SzToPt(int sz) => sz / 2.0;
4041
+
4042
+ // Line spacing helpers
4043
+ public static int SingleSpacing => 240;
4044
+ public static int DoubleSpacing => 480;
4045
+ public static int OneAndHalfSpacing => 360;
4046
+ public static int LineSpacingPt(double pt) => (int)(pt * 20);
4047
+
4048
+ // Common measurements
4049
+ public static int HalfInch => 720;
4050
+ public static int OneInch => 1440;
4051
+ public static int OneAndHalfInches => 2160;
4052
+ public static int TwoInches => 2880;
4053
+ }
4054
+ ```
4055
+
4056
+ ---
4057
+
4058
+ *Document Version: 1.0*
4059
+ *OpenXML SDK: 3.x*
4060
+ *.NET Version: 10*
4061
+ *C# Version: 13*